Fidel_Willis Fidel_Willis - 10 months ago 36
Android Question

How to set text of a view defined in the Main Activity (no XML)

I have a textView that is first created in the Main Activity onCreate file. Like this

Button btn = new Button();

And then I set some attributes of it like an Id and some LayoutParams

btn.setLayoutParams(new ViewGroup.LayoutParams(

So my question is how can I access this Id within the same file to change the text of the button. Like


Except when I do this I get an error. I am assuming since this is not defined within the XML.

EDIT: I cannot pre define these buttons in xml as they are generated based on other factors of the program.

Thank you.


findViewById() gets an integer, so in order to get a reference to your dynamically created TextView, it's enough to pass the same ID to this method.

// Assign it ID 100, for example, when you're creating it

In this example you can find it using:

TextView textView = (TextView) findViewById(100);

Note that findViewById only finds views attached to the hierarchy, so you should make sure you have attached your dynamically created TextView to the hierarchy.

Alternate way: Saving the reference as a class member.

First define a private class member of your MainActivity class. And then initialize it in your onCreate method. So, wherever you need this TextView within the activity class, it's enough to use that class member.

public class MainActivity extends Activity{
    // This is the class member, I was talking about
    private TextView mTextView;

    protected void onCreate(Bundle savedInstanceState) {
         mTextView = new TextView(this);

         mTextView.setLayoutParams(new ViewGroup.LayoutParams(

    public void someMethod(){
        // Here you can reach to that TextView by using its reference saved in mTextView
       mTextView.setText("Hi there!");