vikeyToy 2013-06-28 06:17 采纳率: 0%
浏览 2059
已采纳

在方法范围外使用变量

需要在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条回答 默认 最新

  • 码密码密哄 2013-06-28 06: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去掉

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?