【问题标题】:How to change the image of an ImageButton when the user click the button用户单击按钮时如何更改 ImageButton 的图像
【发布时间】:2017-05-01 00:42:09
【问题描述】:

我花了 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));          
    }

【问题讨论】:

    标签: java android onclick imagebutton


    【解决方案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);
        ...
    }
    

    【讨论】:

    • 这对我有用,非常感谢!我应该先问!哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多