Button variable turns to null after calling method

前端 未结 4 1012
不知归路
不知归路 2021-01-29 11:34

In my mainactivity I have the following snip

MainActivity.class

private Button btnx10;

@Override
protected void onCreate(Bundle savedInstanceState) {
         


        
4条回答
  •  野性不改
    2021-01-29 11:43

    Since you have declared the Button in Scope of Method onCreate()

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

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

    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;
    }
    

提交回复
热议问题