Thursday 27 November 2014

Android : Change Background Color Using Menu Option.

In this tutorial we will learn how add menu option and how to change background color using menu option.

1. Create New Android Application Project. Name it as ColorUsingMenu.
 


2. Open Your activity_main.xml file.
3. Replace your activity_main.xml code with below code.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/Rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change background color using Menu  options.." />

</RelativeLayout>


 Your activity_main.xml will look like below..
 


4 . Open your Mainactivity.java file.

5. Replace Your Mainactivity.java code with below code.


package arshad.colorusingmenu;


import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
       }

         public boolean onOptionsItemSelected(MenuItem item){
              RelativeLayout Ri=(RelativeLayout)findViewById(R.id.Rl);
              if(item.getTitle().toString().equals("RED"))
                     Ri.setBackgroundColor(Color.RED);
              if(item.getTitle().toString().equals("GREEN"))
                     Ri.setBackgroundColor(Color.GREEN);
              if(item.getTitle().toString().equals("BLUE"))
                     Ri.setBackgroundColor(Color.BLUE);
              if(item.getTitle().toString().equals("WHITE"))
                     Ri.setBackgroundColor(Color.WHITE);
              if(item.getTitle().toString().equals("YELLOW"))
                     Ri.setBackgroundColor(Color.YELLOW);
             
              return true;
           }
          
          
          
          
           public boolean onCreateOptionsMenu(Menu menu){
              menu.add("RED").setIcon(android.R.drawable.ic_menu_call);
              menu.add("GREEN");
              menu.add("BLUE");
              menu.add("WHITE");
              menu.add("YELLOW");
              return true;
           }
       }


 6. Now Build And Run Your Application.
  
7. Output screens..






Use menu options to change background colors..


 

All The Best.
 


No comments:

Post a Comment