java 如何在 Android 中通过动态创建为按钮提供 id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7213567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to give id for Button By Dynamic Creations in Android?
提问by pkol
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
我正在尝试通过动态创建一个按钮,我也创建了。现在我想为单击事件编写函数所以我需要按钮的 id。我不知道如何动态地为按钮创建 id。请指导我在此先感谢我的编码
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
sv.addView(ll);
Button main=new Button(this);
CharSequence value="Main +";
main.setText(value);
ll.addView(main);
}
this.setContentView(sv);
}
回答by Dharmendra
You can set id of any controls by
您可以通过以下方式设置任何控件的 id
btn.setId(integer value) at runtime.
If you don't want to set id then there is no issue
如果您不想设置 id 则没有问题
Also when you create new view then you have to set its layout parameters(Height, Width)
此外,当您创建新视图时,您必须设置其 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();
}
});
回答by Mr.Sandy
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.
在那个“ll”是一个布局和那个添加按钮。之后,您可以随时使用单击执行该 clickListener 代码。
回答by Android
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
并且main.setId(pass here int value);
需要设置 id 但我认为你不需要它