I have two buttons on my main Activity, which both should lead to another activity, but when I press my button, it doesn't change anything.
I have all three activities in my manifest:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".UserActivity"
android:label="@string/app_name">
</activity>
<activity
android:name=".ModeratorActivity"
android:label="@string/app_name">
</activity>
Method for the two buttons in my main activity:
private void setUserTypeOnButtonClick(){
Button userButton = findViewById(R.id.button_user);
Button moderatorButton = findViewById(R.id.button_moderator);
userButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
System.out.println("Clicked userbutton");
Intent newActivity = new Intent(v.getContext(), UserActivity.class);
startActivity(newActivity);
}
});
moderatorButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
System.out.println("Clicked moderatorbutton");
Intent newActivity = new Intent(v.getContext(), ModeratorActivity.class);
startActivity(newActivity);
}
});
}
What is the problem here? Did I leave something out?
Edit : Solution is just to
call setUserTypeOnButtonClick()
inside onCreate()
method
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Created activity_main");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUserTypeOnButtonClick();
}
You forgot to call the setUserTypeOnButtonClick()
method after setContentView()
in onCreate()
.
The setContentView()
does make the buttons visible but there is no click listener binding taking place, and hence the buttons don't do anything.
您只需在onCreate
方法中调用setUserTypeOnButtonClick()
您只是忘记了在onCreate()中调用setUserTypeOnButtonClick()
方法
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.