I am writing an android application where the user can add and remove fields interactively. Each field the user add has some buttons, and value which the user should be able to interact with. I thought to create a subclass to handle the field I can add which will hold it's own onClickListener but I'm not sure how to do so.
Here is some pseudo code which should make my intention clear.
Say I have a class , vClass:
public class sClass extends View implements onClickListener{
this.setContextView(R.layout.vClass);//how do I do this in a c开发者_如何学Goorrect way?
@Override
public void onClick(View v){ //add code here
}
}
and aClass which is the main class of the application.
public class aClass extends Activity implements onClickListener{
Button b;
LayoutInflater i;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.b =(Button)this.findViewById(R.id.btn);
b.setOnClickLister(this);
}
@Override
public void onClick(View v){
//this is what I have now to add View
final LinearLayout canvas =(LinearLayout)aClass.this.findViewById(R.id.main);
View cv =this.inflater.inflate(R.layout.counter, canvas, false);
canvas.addView(cv);
}
}
how can I use the vClass to add elements to the aClass.
Typing this is I thought about another solution.
If I keep track of the id's of all the views I have added (without the subcomponents) can I do something of that kind:
View vv = findViewById(id);
Button bb = vv.findViewByIf(R.id.xmlId);
where id is an id I have assigned to the view which I know and xmlId is a string I have specified in the xml file?
Thanks
Yotam
For solution, read the discussion below
IDs used in layouts are not necessarily unique, so i guess you should keep the added Views
in an ArrayList
, as
View cv =this.inflater.inflate(R.layout.counter, canvas, false);
this.viewList.add(cv);
canvas.addView(cv);
or you could declare an index member inside your sClass
implementation, and store the added indices in an ArrayList
:
private int index;
public sClass(final int index)
{
this.index = index;
}
public int getIndex()
{
return this.index;
}
@override
public boolean equals(Object obj)
{
return ((obj instanceof sClass) && (((sClass)obj).getIndex() == this.index));
}
Both ways you have access to the view you want.
The button that lays inside the view is accessible via the findViewById()
method
Button bb = vv.findViewById(R.id.buttonId);
where R.id.buttonId was declared in the vv view's layout xml file, as follows:
<Button android:id="@+id/buttonId" [...] />
精彩评论