Home » Android » Basics of Android Action views

Basics of Android Action views

Welcome to the second and last module of this series. In this module we will learn about basics of android action views, we will learn how to add search action view, how to add custom action view. And at last we will learn how to create tabs using android fragments and action bar.

Below are the topics that we will cover in this module:

  • What is action View?
  • Search action view
  • Custom action view
  • Creating tabs
  • Home Navigation
  • Up Navigation

 

What is action View?

An action view is a widget that appears in the action bar as a substitute for an action button like search box or any other customized UI.

 

Search ActionView

Adding a search box as an actionView is pretty straight, you just need to add android’s searchView widget as actionViewClass.

search_actionview.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menuOption_search"
android:showAsAction="always"
android:title="Search"
android:actionViewClass="android.widget.SearchView">
</item>
</menu>

Above xml will add action view in your application. Now next step is to get the value of searched term and manipulate that according to requirement.

So in you activity class override the onCreateOptionsMenu() method and inflate the view. In the same method get the reference of searchView and then you can apply your logic to manipulate the search term.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   // TODO Auto-generated method stub
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.action_views_2, menu);

   SearchView menuItem = (SearchView)menu.findItem(R.id.menuOption_search);
   View view = menuItem.getActionView();
   // USE the view object to manipulate the data

   return true;
}

In above method I am getting reference of SearchView by using menu.finditem() method, and in the next step I am calling getActionView() method which will return the current action view for this menu item.
And by using this view we can get the search term from searchView and manipulate that value according to the requirement.

 search_action_view

                                                                                                                  Search Action View

Custom Action view

In above example, we used SearchView which is provided by the android itself, but in some scenarios you may feel a need to create a custom action view. In next example, we will create a custom action view by adding ratingBar as a action view item.
To do this first create a custom layout under layout folder.

rating_action_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rating" 
android:layout_gravity="center"/>

<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/customRatingBar" 
android:layout_gravity="center"/>

</LinearLayout>

Now assing this xml to menu item

action_views_2.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menuOption_Rate"
android:showAsAction="ifRoom|collapseActionView"
android:title="Rating"
android:icon="@drawable/ic_action_not_important"
android:actionLayout="@layout/rating_action_view">
</item>
</menu>

In actionLayout config we are passing the rating_action_view.xml

Next step is to create an activity and fetch the data from action view to manipulate it.
ActionViews2.java

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.Toast;

public class ActionViews2 extends Activity implements MenuItem.OnActionExpandListener{

   MenuItem menuItem;
   RatingBar ratingBar;
   Float ratingCount;

@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState); 
   Button btnRateApp = new Button(getApplicationContext());
   btnRateApp.setText("Rate App");
   setContentView(btnRateApp);

   LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
   btnRateApp.setLayoutParams(params);
   btnRateApp.setOnClickListener(new View.OnClickListener() { 
    @Override
    public void onClick(View v) {
     // TODO Auto-generated method stub
     if(menuItem.isActionViewExpanded())
       menuItem.collapseActionView();
     else
       menuItem.expandActionView();
     }
   });
 }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   // TODO Auto-generated method stub
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.action_views_2, menu);

   menuItem = menu.findItem(R.id.menuOption_Rate);
   menuItem.setOnActionExpandListener(this);

   View view = menuItem.getActionView(); 
   ratingBar = (RatingBar)view.findViewById(R.id.ratingBar1);

   return true;
 }

@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
   ratingCount = ratingBar.getRating();
   if(ratingCount<=0){
      Toast.makeText(ActionViews2.this, "Please provide rating", Toast.LENGTH_SHORT).show();
      return false;
   }
   else
     return true;
 }

@Override
public boolean onMenuItemActionExpand(MenuItem item) {
   return true;
 }
}

Above activity has one button called “Rate App”, on click of this button I am checking whether the action bar is expanded or not, if yes then collapse it or else expand it.

In oncreateOptionMenu() I am inflating the view from action_views_2.xml, and getting the reference of ratingBar view.
Now next step is to add the functionality to check whether the user has provided the rating or not, if yes, then allow user to collapse the action view or else notify the user to provide the rating. To do that we should implement MenuItem.OnActionExpandListener which is an interface to handle collapse and expand of action views. Implementing this interface will override the onMenuItemActionCollapse() method which will be called when the action view collapse. In our case, on override of onMenuItemActionCollapse() method I am checking the ratingCount value, if its 0 then display notification to user or else allow the user to collapse the action view.

custom_action_viewCustom Action View

 

Creating tabs

Action bar can be used to create tabbed navigation in you application. For this section, you should have a basic knowledge of fragments, to read about fragments go to this link.

There are 3 steps to create tabbed navigation in your application
1. Create fragment classes

Check this tutorial to know more about fragments – Basics of android fragments

 

2. Create an activity which will hold the reference of these fragments

SimpleTabNavigation.java

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;

import com.codeureka.fragment.types.CustomListFragment;
import com.codeureka.fragment.types.SimpleListFragment;

public class SimpleTabNavigation extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);

   ActionBar actionBar = getActionBar();
   actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

   Fragment simpleListFragment = new SimpleListFragment();
   Fragment customListFragment = new CustomListFragment();

   ActionBar.Tab listFragment = actionBar.newTab()
      .setText("Simple List fragment")
      .setTabListener(new TabListener(simpleListFragment));

   ActionBar.Tab customFragment = actionBar.newTab()
      .setText("Custom List fragment")
      .setTabListener(new TabListener(customListFragment));

   actionBar.addTab(listFragment);
   actionBar.addTab(customFragment);
  }
}

Above class will create two fragments, “Simple List Frgament” and “Custom List fragment”. To create tabs in your application, you should first set the action bar mode to “NAVIGATION_MODE_TABS” and then you should call actionBar.newTab() method to add the tabs. I am calling setText() method to set the title of tab and setTabListner() method which will display the selected tab on screen.

 

3. create tabListener to display the selected tab

TabListener.java

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Fragment;
import android.app.FragmentTransaction;

public class TabListener implements ActionBar.TabListener {

   final String FRAGMENT_TAG="fragment_tag";
   Fragment frag;

   public TabListener(Fragment fragment) {
      // TODO Auto-generated constructor stub
      this.frag = fragment;
    }

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
   // TODO Auto-generated method stub
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
   // TODO Auto-generated method stub
   ft.replace(android.R.id.content, frag, FRAGMENT_TAG);
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
   // TODO Auto-generated method stub
   ft.remove(frag);
 }
}

I have created a TabListener class which will implement ActionBar.TabListener interface. ActionBar.TabListener is invoked whenever the tab is focused, unfocused, added, or removed; other than that you can override its methods to display the animation while navigating from one tab to another.
In above code I am replacing the current tab with newly selected tab and then removing the unselected fragment.

tabsTabs using action bar

 

Home Navigation

icon on action bar can be used as a home button of an application, you can navigate user to home screen by clicking on that icon.

There are 3 steps to do this
1. Add setHomeButtonEnabled() in your activity’s onCreate() method. setHomeButtonEnabled() method will enable or disable the “home” button in the corner of the action bar.

ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);

So your oncreate() method will look like this:

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   ActionBar actionBar = getActionBar();
   actionBar.setHomeButtonEnabled(true);

   setContentView(R.layout.action_bar_activity);
}

2. Add click functionality in onOptionsItemSelected() method.

In onOptionsItemSelected() you need to add one more condition in switch statement:

case android.R.id.home:
   NavUtils.navigateUpFromSameTask(this);
break;

NavUtils.navigateUpFromSameTask() method will navigate the user to Parent Activity, you should define parent activity in your AndroidManifest.xml.

3. Define parent activity in your AndroidManifest.xml

add a <meta-data> tag under your <activity> and define the parent activity.

<activity
android:name="com.codeureka.actionbarexample.BasicActionBarActivity"
android:label="@string/app_name" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.codeureka.examples.ExamplesMainActivity" />
</activity>

 

Up Navigation

Up navigation is almost same as home navigation, using up navigation user can go back to previous activity. To add the up navigation you should call setDisplayHomeAsUpEnabled() on action bar.

Add below code in onCreate() method of your activity for up navigation

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

setDisplayHomeAsUpEnabled() method will display home icon as “Up” icon.

 

So finally we have come to an end of this series, we have tried to cover almost all the major concepts of android action bar. Please comment and let us know if you have any suggestion or if you want us to include more topics.

 Thanks!!! Happy CoDing…

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>