Reputation: 11
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 "
Upvotes: 0
Views: 70
Reputation: 11
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);
}
});
Upvotes: 0
Reputation: 199
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);
}
});
Upvotes: 1