我想显示与按钮对应的textView和知道图像是随机的图像。例如,当显示红色图像并单击按钮btn1
时,将显示textView。
我尝试了这段代码,但textView仍然不可见。
public class colors extends AppCompatActivity {
Button btn1, btn2, btn4;
ImageView img;
TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colors);
img = (ImageView) findViewById(R.id.imageView3);
txt1 = (TextView) findViewById(R.id.txt);
btn1 = (Button) findViewById(R.id.red);
btn2 = (Button) findViewById(R.id.blue);
btn4 = (Button) findViewById(R.id.green); //st.setEnabled(false);
int[] cards = {R.drawable.green, R.drawable.red, R.drawable.blue};
Random r = new Random();
final int n = r.nextInt(3);
img.setImageResource(cards[n]);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (n == 2) {
txt1.setVisibility(View.VISIBLE);
}
}
});
}
答案 0 :(得分:0)
根据我对你的问题的理解,你想要的是:
public class colors extends AppCompatActivity {
Button btn1, btn2, btn3;
ImageView img;
TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imageView3);
txt1 = (TextView) findViewById(R.id.txt);
btn1 = (Button) findViewById(R.id.red);
btn2 = (Button) findViewById(R.id.blue);
btn3 = (Button) findViewById(R.id.green); //st.setEnabled(false);
final int[] cards = {R.drawable.green, R.drawable.red, R.drawable.blue};
Random r = new Random();
final int n = r.nextInt(3);
img.setImageResource(cards[n]);
img.setId(cards[n]);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// green is cards[0], red is cards[1], blue is cards[2]
if (img.getId() == cards[1]) {
txt1.setVisibility(View.VISIBLE);
} else {
// txt1.setVisibility(View.GONE);
}
}
});
}
}
将图像的ID设置为与int数组中的ID (R.drawable.red)
相同。这样,您可以在稍后点击bt1
时进行检查。