Dynamically adding a child to LinearLayout with getting each child's position

前端 未结 2 1956
我在风中等你
我在风中等你 2021-01-02 08:11

I have a problem with getting the child\'s position of LinearLayout. First I\'m adding dynamically a number of buttons and then I\'m trying to return each child\'s

相关标签:
2条回答
  • 2021-01-02 08:40

    You must setContentView before start findViewById

    setContentView(R.layout.main);
    tv = (TextView) findViewById(R.id.text);
    
    0 讨论(0)
  • 2021-01-02 08:57

    your problem is resources.... you use the setText(int) method (that index is int...) which looks for resources and not string, this is not StringBuilder for which you can throw any type and get a string. you needs to replace

    tv.setText(ll.indexOfChild(v));

    with

    tv.setText(Integer.toString(ll.indexOfChild(v)));

    and if you want even little bit of efficiency:

    public class TestActivity extends Activity {
    
        private String[] categories;
    
        private LinearLayout ll;
        private TextView tv;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            categories = getResources().getStringArray(R.array.categories);
    
            tv = (TextView) findViewById(R.id.text);
            ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
    
            for(int i = 0; i < categories.length; i++) {
                Button btn = new Button(this);
                btn.setText(categories[i]);
                btn.setOnClickListener(buttonClick);
                ll.addView(btn);
                int idx = ll.indexOfChild(btn);
                btn.setTag(Integer.toString(idx));
            }
        }
    
        OnClickListener buttonClick = new OnClickListener() {
            public void onClick(View v) {
                String idxStr = (String)v.getTag();
                tv.setText(idxStr);
            }
        };
    
    }
    
    0 讨论(0)
提交回复
热议问题