我需要获取动态生成按钮的id
I need to get the id of the dynamically generating button
根据此代码,它根据另一个布局的给定值创建动态按钮。我需要获取它的 ID 并添加另一个按钮(如果动态按钮单击,那么我需要动态添加另一个按钮)。
for (int i = 0; i < value1; i++) {
LinearLayout.LayoutParams paramsIButton = new LinearLayout.LayoutParams
((int) ViewGroup.LayoutParams.WRAP_CONTENT, (int) ViewGroup.LayoutParams.WRAP_CONTENT);
ibutton = new ImageButton(HomePage.this);
ibutton.setImageResource(R.drawable.add);
ibutton.setLayoutParams(paramsIButton);
paramsIButton.topMargin = -70;
paramsIButton.leftMargin = 370;
paramsIButton.bottomMargin = 30;
ibutton.setId(i);
ibutton.getPaddingBottom();
ibutton.setBackgroundColor(Color.WHITE);
ibutton.setAdjustViewBounds(true);
rR.addView(ibutton);
}
如果我从你在评论中提供的附加信息中理解正确,你需要知道用户何时点击了按钮。您可以为您的按钮设置一个 OnClickListener。
// Somewhere in your activity . . .
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// The button is clicked! Do whatever you want.
}
});
}
// ...
// Rest of the code
// ...
当然,您应该将 R.id.button1
替换为您的按钮 ID。
在我看来,您需要为动态添加的按钮添加一个 onClickListener。
使您的 class 实现 OnClickListener,然后为动态按钮添加侦听器:
ibutton.setOnClickListener(this);
并在您的 class:
中添加一个 onClick 侦听器
@Override
public void onClick(View v)
{
// do something with this ID
v.getId()
}
我不知道您是如何跟踪灯泡和风扇的,我希望您不要仅通过 UI 元素来跟踪。我可能会做一些不同的事情,创建一个数据结构来跟踪灯泡和风扇并将特定的灯泡或风扇对象作为标签附加到 UI 元素。
根据此代码,它根据另一个布局的给定值创建动态按钮。我需要获取它的 ID 并添加另一个按钮(如果动态按钮单击,那么我需要动态添加另一个按钮)。
for (int i = 0; i < value1; i++) {
LinearLayout.LayoutParams paramsIButton = new LinearLayout.LayoutParams
((int) ViewGroup.LayoutParams.WRAP_CONTENT, (int) ViewGroup.LayoutParams.WRAP_CONTENT);
ibutton = new ImageButton(HomePage.this);
ibutton.setImageResource(R.drawable.add);
ibutton.setLayoutParams(paramsIButton);
paramsIButton.topMargin = -70;
paramsIButton.leftMargin = 370;
paramsIButton.bottomMargin = 30;
ibutton.setId(i);
ibutton.getPaddingBottom();
ibutton.setBackgroundColor(Color.WHITE);
ibutton.setAdjustViewBounds(true);
rR.addView(ibutton);
}
如果我从你在评论中提供的附加信息中理解正确,你需要知道用户何时点击了按钮。您可以为您的按钮设置一个 OnClickListener。
// Somewhere in your activity . . .
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// The button is clicked! Do whatever you want.
}
});
}
// ...
// Rest of the code
// ...
当然,您应该将 R.id.button1
替换为您的按钮 ID。
在我看来,您需要为动态添加的按钮添加一个 onClickListener。
使您的 class 实现 OnClickListener,然后为动态按钮添加侦听器:
ibutton.setOnClickListener(this);
并在您的 class:
中添加一个 onClick 侦听器@Override
public void onClick(View v)
{
// do something with this ID
v.getId()
}
我不知道您是如何跟踪灯泡和风扇的,我希望您不要仅通过 UI 元素来跟踪。我可能会做一些不同的事情,创建一个数据结构来跟踪灯泡和风扇并将特定的灯泡或风扇对象作为标签附加到 UI 元素。