调用方法后,Button变量变为null [英] Button variable turns to null after calling method

查看:67
本文介绍了调用方法后,Button变量变为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主要活动中,我有以下片段

In my mainactivity I have the following snip

MainActivity.class

MainActivity.class

private Button btnx10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Button btnx10=(Button)findViewById(R.id.MainCOPbtn);
    DrawLines();
}


private void drawLines(){
   float centerYOnImage1=btnx10.getHeight()/2;
}

我正在尝试从方法drawLines()
中访问在onCreate()方法中创建的按钮 即在同一类MainActivity.class中,但在此方法之外.

I'm trying to access the button that is created in the onCreate() method from the method drawLines()
i.e. in the same class MainActivity.class but outside of this method.

当我尝试访问drawlines()方法中的按钮时,其值为null.

When I am trying to access the button in the drawlines()method it's value is null.

如何访问该按钮?

推荐答案

由于您已在方法范围 onCreate()

Button btnx10=(Button)findViewById(R.id.MainCOPbtn);

,并且您尝试在方法onCreate()之外访问它,这使其在该方法之外不可访问.

and you are trying to access it outside of the method onCreate(), that makes it inaccessible outside of this method.

只需在类级别(全局)上进行引用,并在onCreate()方法中使用相同的引用即可.

Just make the reference on class level (Globally) and use the same Reference in onCreate() method.

您可以执行以下操作:-

you can do this:-

private Button btnx10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnx10 = (Button)findViewById(R.id.MainCOPbtn);
    DrawLines();
}


private void drawLines(){
   float centerYOnImage1 = btnx10.getHeight()/2;
}

这篇关于调用方法后,Button变量变为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆