Android 图像按钮传递参考

Android 图像按钮传递参考,android,reference,imagebutton,Android,Reference,Imagebutton,我试图通过索引数组传递imagebutton作为引用 我想我可以设置ID,然后按如下方式传递该ID: MyButton=(ImageButton) findViewById(R.id.imageButton1); MyButton.setId(0); 然后在我的onClick中,我想传递索引“0”: 索引被传递给方法: boolean Switch_Ctrl(char button_num, byte state){ button_num.setImageResour

我试图通过索引数组传递imagebutton作为引用

我想我可以设置ID,然后按如下方式传递该ID:

MyButton=(ImageButton) findViewById(R.id.imageButton1);
MyButton.setId(0);
然后在我的onClick中,我想传递索引“0”:

索引被传递给方法:

boolean Switch_Ctrl(char button_num, byte state){

            button_num.setImageResource(R.drawable.switch_off);
            button_num.setSelected(false);
}
我收到错误,无法解析方法setImageResource


所以我不能使用id“button_num”。不确定如何引用ImageButton?

您只需存储对按钮的引用,然后单击更改即可。只需将其作为
活动
片段
中的实例变量即可。您可以单独声明一个按钮,然后在创建时将其初始化为
onCreate
onActivityCreated
(一旦findViewById可用)。比如说

private Button myButton;

@Override
protected void onCreate(Bundle savedInstanceState){
    myButton = (Button) findViewById(R.id.button);
    myButton.setOnClickListener(new Button.OnClickListener() {

         public void onClick(View v) {
             changeButtonBackground(v.getId());
         });

     }
 }

//if doing this for multiple butons, check which one
//was pressed and change the background
private void changeButtonBackground(int id){
    if(id == R.id.myButton){
        myButton.setBackground(R.drawable.whatever);
    }
}

此外,我不会将按钮的id设置为0之类的任何其他值。您的按钮已经有一个id,它是您在XML中定义为android:id=“@+id/whateveritis”的id。除非以编程方式创建XML中不存在的视图(例如,如果单击此按钮将TextView添加到某个父布局中),否则不需要定义新id。

按钮\u num
字符
char
没有像
setImageResource()
这样的方法。我推荐一些基本的Java教程,然后回来再试一次。如果您想通过视图的id号引用视图,那么您已经这样做了!(
findViewById
)然而,正确的解决方案是利用
View
,v的实例,该实例被传递给
onClickListener
,它引用了单击的按钮。我简化了我的问题,我有另一个方法,我需要调用Switch\u Ctrl,它不是onCLick,所以我不知道imagebutton是否需要ID…,不管怎样,谢谢你的帮助。。要从id获取imagebutton,我只需使用“imagebutton\u id=(imagebutton)findViewById(button\u num);我很困惑-只需从onClick调用switch controll。问题是您不知道按钮的id,所以不知道需要更改哪个按钮的背景?还是您不知道使用哪个图像作为背景?
private Button myButton;

@Override
protected void onCreate(Bundle savedInstanceState){
    myButton = (Button) findViewById(R.id.button);
    myButton.setOnClickListener(new Button.OnClickListener() {

         public void onClick(View v) {
             changeButtonBackground(v.getId());
         });

     }
 }

//if doing this for multiple butons, check which one
//was pressed and change the background
private void changeButtonBackground(int id){
    if(id == R.id.myButton){
        myButton.setBackground(R.drawable.whatever);
    }
}