简单的dialog菜单

时间:2021-12-02 00:43:03

本文介绍的是我自己做的一个简单的dialog菜单,可以直接植入到类中。

方法代码:

/** 显示一个靠右上的dialog列表菜单*/
private void showTopBarRightButtonDropListDialog() {
  final Dialog dialog = new Dialog(this, R.style.DialogStyle);
  LinearLayout linearLayout = new LinearLayout(this);
  linearLayout.setOrientation(LinearLayout.VERTICAL);
  ViewGroup.LayoutParams params0 = new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.WRAP_CONTENT);
  linearLayout.setLayoutParams(params0);   // 获取屏幕的信息
  DisplayMetrics dm = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(dm);   // 添加子视图
  Button btn1 = new Button(this);
  Button btn2 = new Button(this);
  Button btn3 = new Button(this);
  Button btn4 = new Button(this);
  Button btn5 = new Button(this);
  btn1.setText("1");
  btn2.setText("2");
  btn3.setText("3");
  btn4.setText("4");
  btn5.setText("5");
  LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int)(50 * dm.density));
  btn1.setLayoutParams(params1);
  btn2.setLayoutParams(params1);
  btn3.setLayoutParams(params1);
  btn4.setLayoutParams(params1);
  btn5.setLayoutParams(params1);
  btn1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
dialog.dismiss();
}
});
btn2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
dialog.dismiss();
}
});
btn3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.dismiss();
}
});
linearLayout.addView(btn1);
linearLayout.addView(btn2);
linearLayout.addView(btn3);
linearLayout.addView(btn4);
linearLayout.addView(btn5);
dialog.setContentView(linearLayout);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
setDialogSize(dialog);
}

private void setDialogSize(Dialog dg) {


  Window dialogWindow = dg.getWindow();
  WindowManager.LayoutParams lp = dialogWindow.getAttributes();
  dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
  dialogWindow.setGravity(Gravity.RIGHT | Gravity.TOP);
  //显示的坐标
  lp.x = 150;
  lp.y = 50;
  dialogWindow.setAttributes(lp);
 }


R.Style.DialogStyle内容:

<style name="DialogStyle">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:backgroundDimEnabled">true</item>
</style>

  以上是完整的代码。