Android Menus Example

Leave a Comment
Creating Menus in android
Menus in android are created in the menu folder inside the res folder.
Open the main.xml file in the menu folder and edit it to the following

main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never"/>
    <item
        android:id="@+id/about"
        android:title="About"
       app:showAsAction="ifRoom"
    />
     <item
        android:id="@+id/help"
        android:title="Help"
       app:showAsAction="always"
    />
    

</menu>

MainActivity.java

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Toast.makeText(getApplicationContext(), "Settings Menu",
                    Toast.LENGTH_LONG).show();
        }
        if (id == R.id.about) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("About Me");
            builder.setMessage("I am jahson an android apps developer......");
            builder.show();

        }
        if (id == R.id.help) {

            Toast.makeText(getApplicationContext(), "Help Menu ",
                    Toast.LENGTH_LONG).show();
        }

        return super.onOptionsItemSelected(item);
    }
}

 


 These Menus will appear on the actionbar if there is available room otherwise they can be accessed through the menu Button

0 comments:

Post a Comment