Pages

Tuesday, September 13, 2016

Android Example-Creating Simple Manu Item


activity_main.xml
<RelativeLayout 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"
    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="match_parent"
        android:layout_height="40dp"
        android:text="A Menu Activity"
        android:textSize="30dp"
        android:layout_marginTop="120dp"
        android:gravity="center_vertical|center_horizontal"
        android:id="@+id/textView2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Click Option button in your mobile or Action Bar&apos;s side icon"
        android:id="@+id/textView"
        android:gravity="center_horizontal"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

MainActivity.java
package in.kantapp.example12;

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

public class MainActivity extends AppCompatActivity
{

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main_menu,menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.Menu_label1:
                Toast.makeText(MainActivity.this, "Menu Lable One", Toast.LENGTH_SHORT).show();
                break;
            case R.id.Menu_label2:
                Toast.makeText(MainActivity.this, "Menu Lable two", Toast.LENGTH_SHORT).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }
}

menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/Menu_label1"
        android:alphabeticShortcut="1"
        android:title="Menu_label"/>
    <item
        android:id="@+id/Menu_label2"
        android:alphabeticShortcut="2"
        android:title="Menu_label2"/>
</menu>

No comments:

Post a Comment