Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setOnClickListener error - cannot resolve symbol

I want to create a button which, when clicked, it will show another intent.

This is the code:

   <Button
    android:text="Bine ati venit!"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/button1"
    android:background="#479fc7"
    android:textSize="40dp"
    android:textColor="@color/colorPrimaryDark"
    android:textStyle="normal|bold|italic"
    android:textAllCaps="false"
    android:fontFamily="casual"
    android:onClick="next_page"/>

and from the .java class:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
}

Button button = (Button) findViewById(R.id.button1);

button.setOnClickListener( new View.OnClickListener()
{
    public void onClick (View v){
    next_page(v);
}
});

public void next_page(View v) {
    Intent intent = new Intent(this, MapsActivity.class);
    startActivity(intent);
}

I get the errors: "Cannot resolve symbol 'setOnClickListener'", "variable onClick is never used", "; expected"....

like image 857
rocko Avatar asked Mar 11 '26 07:03

rocko


2 Answers

// You must move the code you type into the class method and work like the following

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the View that shows the numbers category
        TextView numbers = (TextView) findViewById(R.id.numbers);

// Set a click listener on that View
        numbers.setOnClickListener(new View.OnClickListener() {
            // The code in this method will be executed when the numbers View is clicked on.
            @Override
            public void onClick(View view) {
                Intent numbersIntent = new Intent(MainActivity.this, NumberActivity.class);
                startActivity(numbersIntent);
            }
        });
    }
like image 172
Amin Ouchdih Avatar answered Mar 13 '26 20:03

Amin Ouchdih


You should put that particular snippet inside OnCreate(). That solved the issue for me.

like image 36
Anonymous Avatar answered Mar 13 '26 20:03

Anonymous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!