Screenshots :
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<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="com.chantisandroid.exampleapp.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Popup menu"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp" />
</RelativeLayout>
Now create menu folder under res
under menu folder create one xml file
example_menu.xml :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item"
android:title="Android" />
<item
android:id="@+id/item2"
android:title="Java" />
<item
android:id="@+id/item3"
android:title="Oracle" />
<item
android:id="@+id/item4"
android:title="Php" />
<item
android:id="@+id/item5"
android:title="Ios" />
</menu>
MainActivity.java :
package com.chantisandroid.exampleapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.setOnMenuItemClickListener(this);
popupMenu.inflate(R.menu.example_menu);
popupMenu.show();
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "You Clicked : " + item.getTitle(), Toast.LENGTH_LONG).show();
return true;
}
}
No comments:
Post a Comment