Android switch语句只发送1个“key”值

时间:2016-02-29 19:00:50

标签: android

我正在制作一个Android货币转换器应用程序,我的MainActivity上有4个按钮。当单击某个按钮时,我需要它然后将我分配给它的字符串发送到我的MainActivity2,然后在我指定的文本视图中显示它。我可以让它发送1(最后一个案例:声明)所以我尝试了一个if语句,但结果相同....

MainActivity

public void firstCurrencyChoice(View view)
    {
        switch(view.getId())
        {
            case R.id.usdButton:
                Intent a = new Intent(MainActivity.this, Main2Activity.class);
                a.putExtra("key","USD");
                startActivity(a);
                break;

            case R.id.eurButton:
                Intent b = new Intent(MainActivity.this, Main2Activity.class);
                b.putExtra("key", "EUR");
                startActivity(b);
                break;

            case R.id.jpyButton:
                Intent c = new Intent(MainActivity.this, Main2Activity.class);
                c.putExtra("key", "JPY");
                startActivity(c);
                break;

            case R.id.gbpButton:
                Intent d = new Intent(MainActivity.this, Main2Activity.class);
                d.putExtra("key","GBP");
                startActivity(d);
                break;
        }
    }

Main2Activity

@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        final Button btn1 = (Button)findViewById(R.id.optionOneButton);
        final Button all = (Button)findViewById(R.id.converAllButton);
        final TextView firstChoiceTV = (TextView)findViewById(R.id.firstChoiceTV);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main2Activity.this, Main3Activity.class));
            }
        });

        all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main2Activity.this, Main4Activity.class));
            }
        });

        Intent d = getIntent();
        String getA = d.getStringExtra("keyA");
        firstChoiceTV.setText(getA);

        Intent e = getIntent();
        String getB = e.getStringExtra("keyB");
        firstChoiceTV.setText(getB);

        Intent f = getIntent();
        String getC = f.getStringExtra("keyC");
        firstChoiceTV.setText(getC);

        Intent g = getIntent();
        String getD = g.getStringExtra("keyD");
        firstChoiceTV.setText(getD);

    }
}

1 个答案:

答案 0 :(得分:2)

您正在使用键key设置额外内容,但是当您尝试阅读时,您正在使用keyAkeyB阅读其他内容;

只需获取分配给key

的值即可
    String value = getIntent().getStringExtra("key");