切换函数执行多个案例

时间:2015-11-06 19:14:36

标签: android android-intent gridview android-studio

嗨,我一直面临着一个问题,我似乎无法找到解决方案。 我有一个包含三个项目的gridview,每个项目在选中时都会打开一个活动。问题出现在我选择case 0时,首先打开intent i然后打开intent ii,最后打开intent iii

如果我选择case 1,我会先打开intent ii,然后再打开intent iii。 最后,如果我选择case 2,我会打开intent iii。这是主要代码!

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mItems = new ArrayList<GridViewItem>();
        Resources resources = getResources();

        mItems.add(new GridViewItem(resources.getDrawable(R.drawable.truck_package), getString(R.string.drop_package)));
        mItems.add(new GridViewItem(resources.getDrawable(R.drawable.man_package), getString(R.string.pick_package)));
        mItems.add(new GridViewItem(resources.getDrawable(R.drawable.register), getString(R.string.register)));
        mAdapter = new GridViewAdapter(this, mItems);
        // initialize the GridView
        final GridView gridView = (GridView) this.findViewById(R.id.gridView);
        gridView.setAdapter(mAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0 :
                        Intent i = new Intent(getApplicationContext(), DropPackage.class);
                        Toast.makeText(getApplicationContext(), "DropPack", Toast.LENGTH_SHORT).show();
                        startActivity(i);

                    case 1 :
                        Intent ii = new Intent(getApplicationContext(), PickPackage.class);
                        Toast.makeText(getApplicationContext(), "PickPack", Toast.LENGTH_SHORT).show();
                        startActivity(ii);
                    case 2 :
                        Intent iii = new Intent(getApplicationContext(), Register.class);
                        Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();
                        startActivity(iii);
                }



            }
        });
    }

知道可能出现什么问题?谢谢:))

1 个答案:

答案 0 :(得分:0)

您未将break放在案例陈述的末尾。 尝试在每个case语句的末尾添加break。

试试这种方式

switch (position){
    case 0 :
        Intent i = new Intent(getApplicationContext(), DropPackage.class);
        Toast.makeText(getApplicationContext(), "DropPack", Toast.LENGTH_SHORT).show();
        startActivity(i);
        break;

    case 1 :
        Intent ii = new Intent(getApplicationContext(), PickPackage.class);
        Toast.makeText(getApplicationContext(), "PickPack", Toast.LENGTH_SHORT).show();
        startActivity(ii);
        break;

    case 2 :
        Intent iii = new Intent(getApplicationContext(), Register.class);
        Toast.makeText(getApplicationContext(), "Register", Toast.LENGTH_SHORT).show();
        startActivity(iii);
        break;
}