【问题标题】:Android Buttons open up the wrong activitiesAndroid Buttons 打开错误的活动
【发布时间】:2011-05-11 23:46:33
【问题描述】:

我的主页上有三个按钮。当我尝试点击它们时会发生一些奇怪的事情。例如,当我单击 NewGame 按钮时,它首先会显示分数按钮应该显示的内容,然后如果我单击返回按钮,它将继续显示它应该显示的活动。使用 About 按钮,我必须单击两次(它显示 newGame 活动和 score 活动。发生这种情况是否有原因?

public class Sakurame extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    //set up click listeners for buttons
    View HighScoreButton = findViewById(R.id.highscore_button);
    HighScoreButton.setOnClickListener(this);
    View newButton = findViewById(R.id.new_button);
    newButton.setOnClickListener(this);
    View aboutButton = findViewById(R.id.about_button);
    aboutButton.setOnClickListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu){
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
    case R.id.settings:
        startActivity(new Intent(this, Prefs.class));
        return true;
        // More items go here (if any)
    }
    return false;
}

public void onClick(View v){
    switch(v.getId()){
    case R.id.about_button:
        Intent i = new Intent(this, About.class);
        startActivity(i);
    case R.id.new_button:
        Intent i2 = new Intent(this, HighScore.class);
        startActivity(i2);
    case R.id.highscore_button:
        Intent i3 = new Intent(this, DisplayScores.class);
        startActivity(i3);
        //break;

        // more buttons go here (if any)
    }
}

【问题讨论】:

    标签: android button android-activity android-intent


    【解决方案1】:

    尝试在 onClick 方法中的每个 startActivity 之后添加 break;

    编辑澄清。这可确保一旦满足 case,switch 语句就会中断,而不是继续下一个 case 语句。

        case R.id.about_button:
            Intent i = new Intent(this, About.class);
            startActivity(i);
            break;
        case R.id.new_button:
            Intent i2 = new Intent(this, HighScore.class);
            startActivity(i2);
            break;
        case R.id.highscore_button:
            Intent i3 = new Intent(this, DisplayScores.class);
            startActivity(i3);
            break;
    

    【讨论】:

    • 只是为了补充说明:案例陈述级联。因此,如果您不在每个 case 语句后添加 break,则每个后续 case 语句都会运行...
    • 谢谢 - 它解决了一切。我没有意识到他们级联@.@
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多