Android Custom Popup menu with switch

允我心安 提交于 2019-12-05 05:34:14

You can use popupwindow since it allows to use custom layouts.

<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" 
    android:padding="5dp">

<Switch
    android:id="@+id/mySwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp"
    android:text="Play with the Switch" />

<TextView
    android:id="@+id/switchStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/mySwitch"
    android:layout_marginTop="22dp"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

and in ur activity implement this method:

/* you should refer to a view to stick your popup wherever u want.
** e.g. Button button  = (Button) findviewbyId(R.id.btn);
**     if(popupWindow != null)
**         showPopup(button); 
**/
    public void showPopup(View v) {


            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View popupView = layoutInflater.inflate(R.layout.popup_filter_layout, null);

            popupWindow = new PopupWindow(
                    popupView,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);

            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setOutsideTouchable(true);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    //TODO do sth here on dismiss
                }
            });

            popupWindow.showAsDropDown(v); 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!