程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> java-在方法范圍外使用變量

java-在方法范圍外使用變量

編輯:編程綜合問答
在方法范圍外使用變量

需要在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);

最佳回答:


設置成全局的話
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去掉

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved