如何在用户单击按钮时更改 ImageButton 的图像
How to change the image of an ImageButton when the user click the button
我花了 3 个小时试图制作一个 ImageButton,它可以在用户单击时更改其图像,但这对我来说是不可能的。提前致谢!
主类
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton dado_btn = (ImageButton) findViewById (R.id.dado_button);
replace = R.drawable.face_1;
dado_btn.setBackgroundResource(replace);
}
public void OnClickTirada (View v){
//this doesn't work at all
dado_btn.setImageDrawable(getResources().getDrawable(R.drawable.face_1));
}
dado_btn
仅在 onCreate()
中本地定义,因此您不能在任何其他方法中使用它。
要完成这项工作,您必须声明一个字段 dado_btn
,如果您的代码可以编译,您可能已经这样做了。作为第二步,不要在 onCreate()
.
中声明局部变量
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dado_btn = (ImageButton) findViewById (R.id.dado_button);
...
}
我花了 3 个小时试图制作一个 ImageButton,它可以在用户单击时更改其图像,但这对我来说是不可能的。提前致谢!
主类
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton dado_btn = (ImageButton) findViewById (R.id.dado_button);
replace = R.drawable.face_1;
dado_btn.setBackgroundResource(replace);
}
public void OnClickTirada (View v){
//this doesn't work at all
dado_btn.setImageDrawable(getResources().getDrawable(R.drawable.face_1));
}
dado_btn
仅在 onCreate()
中本地定义,因此您不能在任何其他方法中使用它。
要完成这项工作,您必须声明一个字段 dado_btn
,如果您的代码可以编译,您可能已经这样做了。作为第二步,不要在 onCreate()
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dado_btn = (ImageButton) findViewById (R.id.dado_button);
...
}