Search code examples
androidandroid-studioonclicklistenersettext

setText is shown in red and i don't undrestand why


setText is shown in red and i don't undrestand why

public class MainActivity extends AppCompatActivity {

    TextView v = (TextView)findViewById(R.id.textInput);
    Button b = (Button)findViewById(R.id.btn12);
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b.setOnClickListener((new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                v.setText("aaa");// why setText not found
            }
        }));


    }

}

thx


Solution

  • Move these methods:

    TextView v = (TextView)findViewById(R.id.textInput);
    Button b = (Button)findViewById(R.id.btn12);
    

    You can use:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView v = (TextView)findViewById(R.id.textInput);
        Button b = (Button)findViewById(R.id.btn12);
        b.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                v.setText("aaa");// why setText not found
            }
        });
    

    or you can use:

    public class MainActivity extends AppCompatActivity {
    
        private TextView v;
        private Button b;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            v = (TextView)findViewById(R.id.textInput);
            b = (Button)findViewById(R.id.btn12);
            b.setOnClickListener(new View.OnClickListener(){
               @Override
               public void onClick(View view) {
                v.setText("aaa");// why setText not found
               }
            });
    
        }
    
    }