Search code examples
androidandroid-sdk-2.1

Search Textview which is created programmatic


I'm adding TextViews programmatic using a for-loop and use setId(Int int) to set unique id for that perticular Textview. But now I want to search textView on the basis of that id. How can I search?

erorr occurd 'app stopped unexpectedly...' Here is my code.

public class Idtest extends Activity {
    TextView tv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LinearLayout ll=new LinearLayout(this);
        tv=new TextView(this);

        tv.setText("Hello");
        ll.addView(tv);

        tv=new TextView(this);
        tv=(TextView)ll.getChildAt(1);

        setContentView(tv);


    }
}

Solution

  • tv is obviously null at the end (the LinearLayout only has one child, which is at index 0), so you're basically calling setContentView(null) which results in an exception. It's not clear for me what you're trying to do (your code is pretty messed up).

    Supposing you are trying to show multiple TextViews in a LinearLayout, here's my suggestion:

    public class Idtest extends Activity {
        LinearLayout mainLayout;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            mainLayout = new LinearLayout(this);
            setContentView(mainLayout);
    
            for (int i=0; i < 10; i++) {
                TextView tv = new TextView(this);
                tv.setText("Hello " + i);
                mainLayout.addView(tv);
            }
        }
    }
    

    If, at any later point, you need one of the TextViews, do:

    TextView tvX = mainLayout.getChildAt(X); // where X is between 0 and 9
    

    Also, please note that creating layout from code is evil. If you can avoid it, please do. For example, if the number of TextViews is dynamic, then it's perfectly normal to create them from code (although you could inflate them). However, it's not advisable to also create the LinearLayout from code. You should have that in an XML. If it's possible for you to also have the TextViews in an XML, that would be even better.