我试图弄清楚如果参数为真,如何使一个按钮执行不同的功能。例如:
有很多可能性(灵活的用户界面)
public void BuildCars(View view)
{
//Atver buildcarfragmentu.
switch(view.getId())
{
case R.id.button1:
// Set Frame Image, Part Cardviews and button.
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);
Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL10_10());
break;
case R.id.button2:
// Set Frame Image, Part Cardviews and button.
break;
case R.id.button3:
// Set Frame Image, Part Cardviews and button.
break;
}
}
在情况1中,我希望按钮做一件事,在情况2中,我希望按钮做另一件事。
像这儿:
public void BuildCars(View view)
{
//Atver buildcarfragmentu.
switch(view.getId())
{
case R.id.button1:
// Set Frame Image, Part Cardviews and button.
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);
Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL10_10());
break;
case R.id.button2:
// Set Frame Image, Part Cardviews and button.
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);
Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL9_4());
break;
case R.id.button3:
// Set Frame Image, Part Cardviews and button.
break;
}
}
我有两个问题:
问题一:
问题2:
最佳答案
在switch语句之外声明框架,也许在BuildCars()方法中声明,而不是在每种情况下都在Switch语句中声明。即:
public void BuildCars(View view)
{
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Button button= (Button) findViewById(R.id.BCButton);
//Atver buildcarfragmentu.
switch(view.getId())
{
case R.id.button1:
// Set Frame Image, Part Cardviews and button.
Frame.setImageResource(R.drawable.frame_1_6);
button.setOnClickListener(sellTiresLVL10_10());
break;
case R.id.button2:
Frame.setImageResource(R.drawable.frame_1_6);
button.setOnClickListener(sellTiresLVL9_4());
break;
case R.id.button3:
// Set Frame Image, Part Cardviews and button.
break;
}
}
您还错误地使用了点击监听器。您的听众应该看起来像这样:
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
您应该阅读文档以更好地理解onClickListener的使用方式:https://developer.android.com/reference/android/widget/Button.html