简体   繁体   中英

Button and Activity with Android Studio

Hi I'm new to stack overflow and I have difficulty creating the code of a button that opens an activity on Android Studio, could someone help me?

import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button b1 = findViewById(R.id.b1); 
    b1.setOnClickListener(new View.OnClickListener(){
    Intent in = new Intent(MainActivity.this, Ristoranti.class);
    MainActivity.this.startActivity(in);
    });


}
}

Where "Ristoranti" is Activity2, and b1 is the button in the activity_main.xml with this code:

<ImageButton
    android:id="@+id/b1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="button title"
    android:layout_marginStart="54dp"
    android:layout_marginTop="118dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@mipmap/ic_launcher_round" />

Android Studio gives me these errors:

" error: as of release 8, 'this' is allowed as the parameter name for the receiver type only, which has to be the first parameter "

" error: expected "

You need to implement the onClick method on OnClickListener Interface

    Button b1 = findViewById(R.id.b1);
    b1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            Intent in = new Intent(SecondActivity.this, MainActivity.class);
            SecondActivity.this.startActivity(in);
        }
    });

In your XML you r using ImageButton and in your Activity class you init Button instead ImageButton so change your code like below:

ImageButton b1 = findViewById(R.id.b1); 
      b1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            Intent in = new Intent(MainActivity.this, Ristoranti.class);
            startActivity(in);
        }
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM