Sunday, November 13, 2011

Change a textView field after creating an Activity

Problem:
I could not remember how to change the textView field after the start of the program. I got an error that was caused by the int to string conversion. I finally got my code to work and I decided to share it.
I added a button to make the application more interactive


Code:

public class Main extends Activity
{

Button add;
TextView tv;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        add = (Button) findViewById(R.id.button1);
        tv = (TextView) this.findViewById(R.id.TextView01);
     
        tv.setText("0"); //the starting value
     
        add.setOnClickListener(new View.OnClickListener()
        {
        int counter = 0;
        String s = "";
       
@Override
public void onClick(View v)
{
counter++;
s =  Integer.toString(counter); //change to string
tv.setText(s); //the text will be changed here.
}
});
}
====

I am sure that I ran into a better method of adding text to the TextView. I just wanted to publish this here as it might help others getting something running. If you can see any areas where I can refine my code then please post it in the comments.

No comments :

Post a Comment