0

我正在使用以下代码创建一个菜单:

 public class MainActivity extends ListActivity {

String classes[] = {"Add a fight to the card", "Add a fighter", "Edit a fighter"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, classes));

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    switch (position){
        case 0:
                Intent intent = new Intent(MainActivity.this, AddFight.class);
                startActivity(intent);
        case 1:
                Intent intent2 = new Intent(MainActivity.this, AddFighter.class);
                startActivity(intent2);
            }
    }

当我在我的列表中单击时case 0:,intent incase 1:被打开而不是case 0:. 我该如何解决?

4

2 回答 2

4

您需要break在您的 switch 案例中插入一条语句,否则,如所写,您的代码将执行case 0然后立即执行case 1

switch (position)
{ 
    case 0:
        Intent intent = new Intent(MainActivity.this, AddFight.class);
        startActivity(intent);
        break;

    case 1:
        Intent intent2 = new Intent(MainActivity.this, AddFighter.class);
        startActivity(intent2);
        break;
}

注意:严格来说,您不需要breakin case 1。但是,这样做是一种很好的做法。case此外,如果您稍后添加其他语句,这将防止“失败” 。

于 2013-10-13T01:27:51.007 回答
1

您的代码将背靠背启动活动。为 case 语句插入 break 然后它将起作用。最后一个 case 语句不需要有 break 语句。

switch (position){
        case 0:
                Intent intent = new Intent(MainActivity.this, AddFight.class);
                startActivity(intent);
                break;
        case 1:
                Intent intent2 = new Intent(MainActivity.this, AddFighter.class);
                startActivity(intent2);
            }
    }
于 2013-10-13T03:30:45.677 回答