Reputation: 61
I want to create multiple views of same type.I have created one view.
LinearLayout mainRoot = (LinearLayout) findViewById(R.id.wrapper);
This is the parent layout.I want to create multiple view under main root.I can use add method to add custom view.But how am i supposed to work out with resource id.
I don't know how to access individual items, as they all have the same id.
Thanks.
Upvotes: 0
Views: 748
Reputation: 15414
You can set some tag to those views that you create by using the setTag() method.
And then when you want to access those views you could use findViewWithTag() to get the view that you are looking for.
UPDATE:
LinearLayout mainRoot = (LinearLayout) findViewById(R.id.wrapper);
for (int i = 0; i < numCustomViews; i++) {
View customView = new View(this);
customView.setTag(i);
mainRoot.addView(customView);
}
// Find view with tag 4
View view5 = mainRoot.findViewWithTag(4);
Log.d("XXX", view5.toString());
Upvotes: 1
Reputation: 147
Use RecyclerView instead of custom View. 1. you can add and remove from RecyclerView. 2. you will get the ClickEvent. 3. Recycler View can be Vertically or horizontally on your requirement.
Go through this Sample of RecyclerView
Upvotes: 1
Reputation: 2885
what you can do is to set the id for each View By using setId
Button btn=new Button(this);
btn.setId(1);
Button btn1=new Button(this);
btn.setId(2);
your_linear_Layout.add(btn);
your_linear_Layout.add(btn1);
now in your onClick method
@Override
public void onClick(View v) {
switch(v.getId()){
case 1:
//btn clicked
break;
case 2:
// btn1 clicked.
break;
}
}
Upvotes: 1