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
You must setContentView before start findViewById
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.text);
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);
}
};
}