Saturday, 1 September 2012

Find length of String in Android example.

main.xml

<?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:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text" android:inputType="text">
    <requestFocus></requestFocus>
</EditText>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/len" android:text="Length" android:onClick="length"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rev" android:text="Reverse" android:onClick="reverse"></Button>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/tv"></TextView>
</LinearLayout>

.java


package com.length_string;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Length_stringActivity extends Activity {
    /** Called when the activity is first created. */
   
private EditText t=null;
private TextView tv=null;
private String s=null;
private int i;


    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        t=(EditText)findViewById(R.id.text);
        tv=(TextView)findViewById(R.id.tv);
    }
   
    public void length(View v)
    {
    s=t.getText().toString();
    //StringBuffer s1=new StringBuffer(s);
    i=s.length();
   
    tv.setText(String.valueOf(i));
    }
   
    public void reverse(View v)
    {
    s=t.getText().toString();
    StringBuffer s1=new StringBuffer(s);
    tv.setText(s1.reverse());
    }
   
}


No comments:

Post a Comment