Thursday, March 1, 2012

Android count character in a string


This program is for to count character in a string. It will return the length of the string.
And if the length is 5 then it will show characte is greater than five.


Step 2)Here is your main java file.


package add.number;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.lang.*;;


public class AddActivity extends Activity {
      
       Button button1;
    EditText txtbox1;
    TextView tv;
      
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
        txtbox1=  (EditText)findViewById(R.id.txtbox1);
        button1 = (Button) findViewById(R.id.button1);
        tv = (TextView) findViewById(R.id.lbl1);
        button1.setOnClickListener(new clicker());
      
       
    }
   
    class clicker implements Button.OnClickListener
    {
    public void onClick(View v)
    {
       String a;
       Integer len;
       a = txtbox1.getText().toString();
       len=a.length();
                    
       if(len > 5 )
       {
              tv.setText("More than 5 character");
       }
       else
       {
              tv.setText("Less than 5 character");
       } 
      
      
      
    }
    }
   
   
}


Step 2)Put below code in your main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

   
<EditText
android:id="@+id/txtbox1"
android:layout_width="145px"
android:layout_height="40px"
android:text="EditText"
android:textSize="18sp"
android:layout_x="75px"
android:layout_y="54px"
> 
</EditText>


<Button
android:id="@+id/button1"
android:layout_width="106px"
android:layout_height="36px"
android:text="Button"
android:layout_x="88px"
android:layout_y="224px"
> 
</Button>

<TextView
android:id="@+id/lbl1"
android:layout_width="141px"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_x="76px"
android:layout_y="166px"
> 
</TextView>
   
 
</LinearLayout>

No comments:

Post a Comment