Tuesday, February 5, 2008

Changing TextView to receive user input programatically

TextView is the ancestor of EditText component. I've try to make TextView from XML design screen to receive input from user still is unsuccessful. But Programatically, i can change the TextView able to receive user input.

To do this, just create activity folder with activitycreator and modify the main activity class, say we have Sample Class below:

public class SampleTextView extends Activity
{
/** Called with the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
TextView v = new TextView(this);
v.setLayoutParams(params);
v.setInputMethod(TextInputMethod.getInstance());
v.setMovementMethod(ArrowKeyMovementMethod.getInstance());
v.setFocusable(true);
v.setText("TEST");
v.setBackgroundColor(0x88FFFF00);
setContentView(v, params);

}
}

Things you have to note is :
  1. Set the TextView to receive focus ( setFocusable )
  2. Set the Input Method to know how method will be used ( setInputMethod )
  3. Set the Movement Method to know how to handle cursor pointer ( setMovementMethod )


Compile and run the program, you can edit the content of TextView.
Good Luck !

Do you want to learn more ?
Learning with sample code ?
Learning by Doing ?
Just Visit http://learncodes.googlepages.com/
and there is Android UI Design at there.

1 comment:

  1. Or you can make EditText look like TextView but still behave like EditText:

    EditText
    style="?android:attr/textViewStyle"
    android:background="@null" android:textColor="@null"

    ReplyDelete

bhayangkara@gmail.com