【发布时间】:2022-02-23 19:40:05
【问题描述】:
代码如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ImageView button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (ImageView)findViewById(R.id.startButton);
button.setOnClickListener(this);
button.setImageResource(R.drawable.play);
}
public void onClick(View v) {
button.setImageResource(R.drawable.pause);
}
}
显然,如果我将 button.setImageResource(R.drawable.pause); 放在 onCreate 中,它可以工作并更改图像,但不能在 onClick 中?我尝试调试它,它运行了 onClick 代码,但没有更改按钮图像。我可能犯了一个非常愚蠢的错误,但我无法弄清楚。
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.larry.app.MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/startButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true" />
</LinearLayout>
【问题讨论】:
-
请向我们展示您的 xml
-
我不认为它是 xml
-
我在一个例子中重做了你的代码,它工作正常(setImageResource 工作)。你没有添加其他的东西吗?
-
我实际上不认为theres任何其他会影响它。奇怪的是 button.setImageResource(R.drawable.pause);在 onCreate() 中有效,但在 onClick() 中有效,即使 onClick() 正在被调用,我很确定
标签: android