Badblog

welcome to our blog

We are Learncodz.


Posts

Comments

The Team

Blog Codz Author

Connect With Us

Join To Connect With Us

Portfolio

    Posted by: Unknown Posted date: 03:17 / comment : 0

    Action Bar in Android is used to provide navigation and to perform some actions. In this tutorial we are going to implement a Simple Action Bar in our Android Application and perform actions such as switching fragments , speech recognition. More Advanced implementation will be covered in another article.  To support older version of Android use Android Support Library.
    Action Bar in WhatsApp Android Application.
    Creating Project
    I am using Android Studio IDE for creating the project. Create a new Android Application with package as com.amal.androidactionbar.app and select theme as Holo Light with Dark Action Bar. Also create main activity as MainActivity and main layout as activity_main.
    Adding Action Bar Items
    Download the Android Action Bar icon pack from Android developers website for using in Action Bar.
    The Action Bar items should be added in the xml file and placed in menu folder. The default file is menu. Each item should be added with <item> tag. Each item has its own id. The “icon” specifies the icon which should be displayed in Action Bar. The “title” specifies the name which should be displayed in Action Bar. The “showAsAction” specifies the display property.
    showAsAction = “ifRoom” – Displays item in Action Bar if space is available.
    showAsAction = “never” – Never displays item in Action bar
    main.xml
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item android:id="@+id/action_speech"
            android:icon="@drawable/ic_action_microphone"
            android:showAsAction="ifRoom"
            android:title="Speech"/>
        <item android:id="@+id/action_call"
            android:icon="@drawable/ic_action_call"
            android:showAsAction="ifRoom"
            android:title="Call"/>
        <item android:id="@+id/action_done"
            android:icon="@drawable/ic_action_done"
            android:showAsAction="ifRoom"
            android:title="Done"/>
        <item android:id="@+id/action_contacts"
            android:showAsAction="never"
            android:title="Contacts"/>
        <item android:id="@+id/action_settings"
            android:showAsAction="never"
            android:title="Settings"/>
        <item android:id="@+id/action_status"
            android:showAsAction="never"
            android:title="Status" />
    </menu>
    Creating Fragment Layouts
    Our MainFragment Layout has a TextView to display Text. It will be dynamically added to the main layout.
    main_fragment.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="40dp"
            android:text="Main Layout"/>
    </LinearLayout>
    Our next fragment layout is text_fragment which also has a TextView to display Text.
    text_fragment.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40dp"
        android:id="@+id/txt"/>
    </LinearLayout>
    Creating Fragment Classes
    Our MainFragment extends to Fragment and uses LayoutInflator to display layout.
    MainFragment.java
    package com.amal.androidactionbar.app;
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    public class MainFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.main_fragment, container, false);
            return view;
        }
    }
    Our TextFragment will be called when the done button in Action Bar is pressed. We retrive the arguments which is passed using bundle and display it in TextView.
    TextFragment.java
    package com.amal.androidactionbar.app;
    import android.os.Bundle;
    import android.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    public class TextFragment extends Fragment {
        TextView text;
        @Override
        public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.text_fragment, container, false);
            text= (TextView) view.findViewById(R.id.txt);
            String menu = getArguments().getString("Menu");
            text.setText(menu);
            return view;
        }
    }
    Creating Main Layout
    Our main layout activity_main has a FrameLayout which would be replaced Dynamically in Activity.
    activity_main.xml
    <LinearLayout 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"
        tools:context=".MainActivity">
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    Creating MainActivity and Performing Actions
    We use onCreateOptionsMenu() method to create the Action Bar menu and MenuInflator to display the menu.
    Then we use onOptionsItemSelected() method to perform actions for the clicks. We get the id of the item using getItemId() method. We use switch case or you can also use if else statements to perform actions. When Contacts , Settings , Status items are pressed a toast is displayed. When Call is pressed the Dialer Intent is opened. When microphone icon is pressed Speech Recognizer Intent is opened for getting voice as Input and the result is displayed in Toast. When done is pressed the MainFragment is replaced with TextFragment.
    MainActivity.java
    package com.amal.androidactionbar.app;
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.Intent;
    import android.os.Bundle;
    import android.speech.RecognizerIntent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Toast;
    public class MainActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Fragment main = new MainFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, main);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            switch (id) {
                case R.id.action_call:
                    Intent dialer= new Intent(Intent.ACTION_DIAL);
                    startActivity(dialer);
                    return true;
                case R.id.action_speech:
                    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                    startActivityForResult(intent, 1234);
                    return true;
                case R.id.action_done:
                    Bundle args = new Bundle();
                    args.putString("Menu", "You pressed done button.");
                    Fragment detail = new TextFragment();
                    detail.setArguments(args);
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
                    return true;
                case R.id.action_contacts:
                    Toast.makeText(getApplicationContext(),"Contacts Clicked",Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.action_settings:
                    Toast.makeText(getApplicationContext(),"Settings Clicked",Toast.LENGTH_SHORT).show();
                    return true;
                case R.id.action_status:
                    Toast.makeText(getApplicationContext(),"Status Clicked",Toast.LENGTH_SHORT).show();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 1234 && resultCode == RESULT_OK) {
                String voice_text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS).get(0);
                Toast.makeText(getApplicationContext(),voice_text,Toast.LENGTH_LONG).show();
            }
        }
    }
    Creating Manifest
    Add the following permission to your AndroidManifest.xml file for performing Voice Recognition Operation.
    android.permission.INTERNET
    App in Portrait Mode. Done item in Action bar is hidden because less space.
    Result of Speech Recognition.
    Happy coding
    If you wish to receive new articles related to Implementing Android Action Bar - Example enter your email address in the field below and subscribe:

    icon allbkg

    Tagged with:

    Next
    Newer Post
    Previous
    Older Post

    No comments:

Comments

The Visitors says
Download Free Software Latest Version