I\'ve added a button to my activity XML file and I can\'t get it to open my other activity. Can some please tell me step by step on how to do this?
Apply the following steps:
mainactivity.java
public void openWindow2(View v) {
//call window2
setContentView(R.layout.window2);
}
}
Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
startActivity(i);
}
});
I did the same that user9876226 answered.
The only differemce is, that I don't usually use the onClickListener. Instead I write following in the xml-file: android:onClick="open"
open
is the function, that is bound to the button.
Then just create the function open() in your activity class. When you click on the button, this function will be called :)
Also, I think this way is more confortable than using the listener.
use the following code to have a button, in android studio, open an already existing activity.
Button StartButton = (Button) findViewById(R.id.YOUR BUTTONS ID GOES HERE);
StartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, YOUR ACTIVITY'S ID GOES HERE.class));
}
});
Inside your Activity
instance's onCreate()
method you need to first find your Button
by it's id using findViewById()
and then set an OnClickListener
for your button and implement the onClick()
method so that it starts your new Activity
.
Button yourButton = (Button) findViewById(R.id.your_buttons_id);
yourButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}
});
This is probably most developers preferred method. However, there is a common alternative.
Alternatively you can use the android:onClick="yourMethodName"
to declare the method name in your Activity
which is called when you click your Button
, and then declare your method like so;
public void yourMethodName(View v){
startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
}
Also, don't forget to declare your new Activity
in your manifest.xml
. I hope this helps.
References;
If you declared your button in the xml file similar to this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next activity"
android:onClick="goToActivity2"
/>
then you can use it to change the activity by putting this at the java file:
public void goToActivity2 (View view){
Intent intent = new Intent (this, Main2Activity.class);
startActivity(intent);
}
Note that my second activity is called "Main2Activity"