如何将char1从onCreate方法传递到另一个方法-在这种情况下,将其传递到selectChar2?我可以将char1和char2全局化吗?我不确定执行此操作的正确方法是什么。请帮忙!

private String char1,char2; // does this even do anything? I thought this would let me use char1 and char2 anywhere.

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

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String char1 = (String) extras.getString("char1"); //is the (String) necessary?

        TextView textView = (TextView) findViewById(R.id.header);

        textView.setText(char1+" vs "+"char2");

    }


}

public void selectChar2(View v) {
    Button btn = (Button)v;
    String char2 = btn.getText().toString();
    Intent intent = new Intent(PickChar2.this, DisplayMatchUp.class);
    Bundle extras = new Bundle();

    extras.putString("Character1",char1); //char1 here is null...how do I get the value from the method above?
    extras.putString("Character2", char2);

    intent.putExtras(extras);
    startActivity(intent);

最佳答案

实际上,您已经声明并使用了两个单独的变量:


一个实例变量:char1
局部变量:char1


1的作用域为类实例(可在类中的任何非静态作用域中访问)。 2定义在定义它的块中。在这种情况下,只需不创建局部变量,而使用实例变量,

    char1 = (String) extras.getString("char1");

09-28 14:56