Fidel_Willis Fidel_Willis - 3 months ago 14
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.setText("Button");
btw.setId("btn");
btn.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));


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

findViewById(R.id.btn);


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.

Answer

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
btw.setId(100);

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         mTextView = new TextView(this);
         mTextView.setText("Button");

         mTextView.setLayoutParams(new ViewGroup.LayoutParams(
             ViewGroup.LayoutParams.WRAP_CONTENT,
             ViewGroup.LayoutParams.WRAP_CONTENT));
    }


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