Learn how to add a Toggle Button to the Navigation Drawer

In order to add the Toggle button to your App you need to follow these steps

1. Add the following code to the Activity class

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

2. Override the onPostCreate method

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}

3. Override the onConfigurationChanged method

@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}

4. Add following snippet to onOptionsItemSelected

if(mActionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}

Follow the Video to gain better understanding. You can refer to the source code here

Android Basics : Why an onClickListener is better than android:onClick

In your App you might be having UI elements like buttons on click of which some action happens in the background.

Let’s take a button for example.

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/testButtonId"
    />

There are two ways to handle events on Button click. One is to define an android:onClick attribute in the layout xml file and specify the method in the Java class.

android:onClick="testMethod"

The problem with this approach is Рif you have buttons defined in a Fragment then you need to define corresponding methods in the Activity class. This will lead to tight coupling between Activity and Fragment.

To avoid this use a onClickListener.

For this you need to implement an onClickListener and bind the Button to this.

Follow the video and refer to the source code here to understand this better.

Android Basics – Add a Button and display a Toast on click

Time for some Action. Let’s add a Button to the Layout XML file and on click of button let’s display a message to the user.

Simple Steps

Add a Button component to the XML file.

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/buttonId"
    android:text="Click Me"
    android:onClick="clickMe"
    android:layout_margin="15dp"/>



Add a method to the MainActivity class.

public void clickMe(View view){
    Toast.makeText(MainActivity.this, "Button Clicked !!", Toast.LENGTH_SHORT).show();
}

You are all set. Test your app now.

Source Code  

https://github.com/ankur-srivastava/HelloAndroid/tree/master/app/src/main/java/com/edocent/helloandroid