2 vikeytoy vikeyToy 于 2013.06.28 14:17 提问

在方法范围外使用变量

需要在onCreate方法之外传递char1到另一个方法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);

1个回答

cj6585256
cj6585256   2013.06.28 14:41
已采纳

设置成全局的话
private String char1,char2;
@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");
//上面修改为char1 = (String) extras.getString("char1");
TextView textView = (TextView) findViewById(R.id.header);

}

}

textView.setText(char1+" vs "+"char2");//这句话你就得等char1 char2都赋值完成后才能设置了

public void selectChar2(View v) {
Button btn = (Button)v;
String char2 = btn.getText().toString();//这个也得把String去掉

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!