how to give id for Button By Dynamic Creations in Android?
I am trying to create a button by Dynamically and also i created .Now i want to write the function for click Event So i need the id for Button.I Dont know How to Create id for button Dynamically.Guide me Thanks in Advance Here My coding
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
l开发者_C百科l.setOrientation(LinearLayout.HORIZONTAL);
sv.addView(ll);
Button main=new Button(this);
CharSequence value="Main +";
main.setText(value);
ll.addView(main);
}
this.setContentView(sv);
}
You can set id of any controls by
btn.setId(integer value) at runtime.
If you don't want to set id then there is no issue
Also when you create new view then you have to set its layout parameters(Height, Width)
for example
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
So whole process is like
Button btn = new Button(Context);
btn.setId(1);
btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setText("Dynamic button");
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(),"Dynamic button is clicked", 3000).show();
}
});
Try this code.
Button text = new Button(this);
text.setId(1);
text.setText("text here");
ll.addView(text);
text.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int id = arg0.getId(); // you get ID of your dynamic button
Toast.makeText(getApplicationContext(), "Dynamic textview!", Toast.LENGTH_SHORT).show();
}
});
In that "ll" is a Layout and that add button. after that you use anytime for click execute that clickListener code.
you can simply use this
Button main= new Button(this);
main.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
and there is main.setId(pass here int value);
to set id but i think you will not need it
精彩评论