Monday, 12 January 2015

Option menus Example






Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Menus Examaple</string>
    <string name="action_settings">Settings</string>
    <string name="action_share">Share</string>
    <string name="hello_world">Hello World!</string>

</resources>

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

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>
    <item android:id="@+id/action_share"
        android:orderInCategory="101"
        android:showAsAction="never"
        android:title="@string/action_share"
        />

</menu>

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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/ hello_world " />

</RelativeLayout>

MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

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

     }

     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
           getMenuInflater().inflate(R.menu.main, menu);
           return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
           if (R.id.action_settings == item.getItemId()) {
                Toast.makeText(getApplicationContext(),
                           "You have clicked on settings", Toast.LENGTH_LONG).show();

           } else if (R.id.action_share == item.getItemId()) {
                Toast.makeText(getApplicationContext(),
                           "You have clicked on share", Toast.LENGTH_LONG).show();
           }

           return super.onOptionsItemSelected(item);
     }   
}

No comments:

Post a Comment