我有两个ImageButton视图,redButton和blueButton,但是在代码中我只使用了一个定义
ImageButton GButton = (ImageButton) findViewById(R.id.blueButton);然后在clickListener中我有以下代码:
GButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case (R.id.blueButton):
GButton = (ImageButton) findViewById(R.id.redButton);
break;
case (R.id.redButton):
GButton = (ImageButton) findViewById(R.id.blueButton);
break;
}
}
});我想让clickListener切换到redButton。但事实并非如此。
发布于 2016-07-05 05:14:05
答案:
是的,您可以通过在两个按钮之间切换来使用两个按钮的一个定义。
问题:
您的代码无法工作,因为在切换id的 of GButton之后,您还没有设置clickListener。
这样做,它就会开始起作用:
GButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case (R.id.blueButton):
Toast.makeText(MainActivity.this, "blue", Toast.LENGTH_SHORT).show();
GButton = (ImageButton) findViewById(R.id.redButton);
//ADD IT HERE
GButton.setOnClickListener(this);
break;
case (R.id.redButton):
Toast.makeText(MainActivity.this, "red", Toast.LENGTH_SHORT).show();
GButton = (ImageButton) findViewById(R.id.blueButton);
//ADD IT HERE
GButton.setOnClickListener(this);
break;
}
}
});发布于 2016-07-05 04:46:18
是的,您可以通过setTag()方法使用,并通过getTag()方法在onClick中检查新标记。
还有另一种建议,即ViewFlipper在一个和另一个之间切换。
这就是其中的一个例子:
<ViewFlipper android:id="@+id/viewFlipper">
<RelativeLayout>
// Red Button
</RelativeLayout>
<RelativeLayout>
// Green Button
</RelativeLayout>
</ViewFlipper>希望它能帮到你。
发布于 2016-07-05 04:42:15
在onClick方法中,您应该重置视图setOnClickListener方法
https://stackoverflow.com/questions/38195268
复制相似问题