So this is my first app and I am trying to code and need some help with buttons. After searching for a answer I just couldn't find one that I understood. I want to be able to make different pages for the app and make imagebuttons
that link to these pages. This is the very basic code I have at the minute for my button. Please try to explain where to put the code etc.
Thanks in advance.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:background="@drawable/home_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:nestedScrollingEnabled="true" />
</RelativeLayout>
Since this is your first app, let's start it simple with using only Activities.
You start with a MainActivity, which shall contain your ImageButtons. By clicking on one of these buttons, you will be directed to another activity. If you press the back button, you will arrive back at your MainActivity.
I shall demonstrate some code which shows you how to navigate from one activity to another one. First add the two activities so your AndroidManifest.xml will look something like this:
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="@string/title_activity_second_activitity" >
</activity>
If you're using AndroidStudio, it will do this for you when you create a new activity.
Your MainActivity.java will look something like this:
public class MainActivity extends Activity {
//Define your views
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find your views
imageButton = (ImageButton) findViewById(R.id.image_button);
//Assign a listener to your button
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Start your second activity
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}
Repeat these steps for every Activity you want to add to your application. For more information, you will find the Android Docs an usefull source. Please check this link out as a start.
Good luck!