【发布时间】:2021-09-01 18:33:55
【问题描述】:
我已经为 Toast.makeText 配置了我编写的一个简单程序所需的所有参数。
在我的程序中,有两个图像视图 + 图像按钮,单击后会切换到不同的背景图像。当按钮的背景图像相同时,我设置了一个条件来推送 toast 通知。
这是我的 MainActivity.java 文件:
package com.example.projectName;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//declare ImageButton here
ImageButton imageButton;
ImageButton imageButton2;
//variable for toggling state
boolean isClicked = false;
boolean isClicked2 = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize ImageButton here
imageButton = findViewById(R.id.image_1);
imageButton2 = findViewById(R.id.image_2);
}
public void foo(View v) { //first image View
if (isClicked) {
imageButton.setImageResource(R.drawable.imageFileName);
//reverse button state
isClicked = false;
} else {
imageButton.setImageResource(R.drawable.imageFileName2);
//reverse button state
isClicked = true;
}
if (isClicked == isClicked2) {
Toast.makeText(this, "test", Toast.LENGTH_LONG).show();
}
}
public void bar(View v) { //second image view
if (isClicked2) {
imageButton2.setImageResource(R.drawable.imageFileName);
//reverse button state
isClicked2 = false;
} else {
imageButton2.setImageResource(R.drawable.imageFileName2);
//reverse button state
isClicked2 = true;
}
if (isClicked == isClicked2) {
Toast.makeText(this, "test", Toast.LENGTH_LONG).show();
}
}
}
这是我定义 imageButtons 的 activity_main.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- android:background stores imageFileName.png -->
<ImageButton
android:id="@+id/image_1"
android:tag="12"
android:onClick="foo"
android:background="@drawable/imageFileName"
android:layout_width="50dp"
android:layout_height="50dp">
</ImageButton>
<ImageButton
android:id="@+id/image_2"
android:tag="13"
android:onClick="bar"
android:background="@drawable/imageFileName2"
android:layout_width="50dp"
android:layout_height="50dp">
</ImageButton>
</LinearLayout>
</LinearLayout>
这是虚拟设备输出:
由于两张图片相同,应该会显示一个 toast 通知。
【问题讨论】:
-
您是否尝试过使用断点或日志来调试您的应用程序?
isClicked == isClicked2是真的吗? -
if (isClicked && isClicked2) -
这只发生在模拟器上吗?如果是这样,这个问题可能会有所帮助stackoverflow.com/questions/61277598/…
-
不是我,而是@CSmith 在此处第三条评论的链接中告诉您冷启动。我读了它,我以为你没有。所以感谢并邀请他。
-
将这个问题作为一个副本结束更合适,但我很高兴能提供帮助!