In this tutorial we will create 4 files. (main.xml, Main.java, second.xml, Second.java)
The idea is simple, click a button on main screen and go to second screen.
Main files :
Add a button to your main.xml file and give it id button1.
In you main.java file find onCreate method and add this code
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Second.class));
}
});
}
So we can easily find button on our main screen using findViewById method.
Then we add listener to a button and if someone click the button we lunch startActivity method.
startActivity method accept Intent(ourcontext, class we want to lunch) as a parameter.
Second files:
Now create second.xml and second.java
In second.xml add another button so you can go back to your main screen and set id to back.
It is a good idea to use strings resources, so in strings addnew String MainMenu and add value "Main".
In your second.xml file add this to your button:
android:text="@string/MainMenu"
Add code in second.java file:
@Override
protected void onCreate(Bundle
savedInstanceState) {
// TODO Auto-generated
method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button
button = (Button) findViewById(id.back);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Second.this, Main.class));
}
});
}
We added to second.java file setContentView(R.layout.second), this is layout that our class will use(second.xml).
Now the last very important think is modifying the AndroidManifest.xml
We have to add our activity:
<activity
android:name=".Second"
android:label="@string/second_title">
</activity>
Thanks for following tutorial.
Adam Bielecki
No comments:
Post a Comment