Tuesday, 6 March 2018

Popup in Android

Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu.The android.widget.PopupMenu is the direct subclass of java.lang.Object class. See The Example Below Java File ActivityMain.java: - package safal.bhatia.PopupMenu; 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.webkit.WebView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView txt_view,you_click; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt_view = (TextView) findViewById(R.id.txt_view); you_click = (TextView) findViewById(R.id.you_click); txt_view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popupMenu = new PopupMenu(MainActivity.this, txt_view); popupMenu.getMenuInflater().inflate(R.menu.pop_up, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { you_click.setText("You Click "+item.getTitle()); return true; } }); popupMenu.show(); } }); } } XML File activity_main: - <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context="safal.bhatia.PopupMenu.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:id="@+id/txt_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:textColor="#000000" android:textSize="20dp" /> </LinearLayout> <TextView android:id="@+id/you_click" android:layout_width="match_parent" android:gravity="center" android:layout_marginBottom="10dp" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:textColor="#000000" android:textSize="20dp" /> </RelativeLayout> Menu File: - First right click on res>new >Android resource directory. And give the name for popup menu then Press ok. Menu File pop_up.xml : - <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/rate" android:title="Rate Us"/> <item android:id="@+id/about" android:title="About"/> <item android:id="@+id/more" android:title="More Details"/> <item android:id="@+id/exit" android:title="Exit"/> </menu>    

No comments:

Post a Comment