Skip to content

Instantly share code, notes, and snippets.

@nein37
Created August 10, 2014 09:27
Show Gist options
  • Save nein37/ae13b1493f97d6ff5d13 to your computer and use it in GitHub Desktop.
Save nein37/ae13b1493f97d6ff5d13 to your computer and use it in GitHub Desktop.
PopupWindowで画面内にダイアログ風の表示をする方法 ref: http://qiita.com/nein37/items/cc4fe1dc4f9527f8dd59
mPopupWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
private PopupWindow mPopupWindow;
@Override
public void onClick(View v) {
mPopupWindow = new PopupWindow(MyActivity.this);
// レイアウト設定
View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
popupView.findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
}
});
mPopupWindow.setContentView(popupView);
// 背景設定
mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_background));
// タップ時に他のViewでキャッチされないための設定
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setFocusable(true);
// 表示サイズの設定 今回は幅300dp
float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());
mPopupWindow.setWindowLayoutMode((int) width, WindowManager.LayoutParams.WRAP_CONTENT);
mPopupWindow.setWidth((int) width);
mPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// 画面中央に表示
mPopupWindow.showAtLocation(findViewById(R.id.show_button), Gravity.CENTER, 0, 0);
}
@Override
protected void onDestroy() {
if (mPopupWindow != null && mPopupWindow.isShowing()) {
mPopupWindow.dismiss();
}
super.onDestroy();
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<stroke
android:width="2dp"
android:color="@android:color/black" />
</shape>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="PopupWindow表示" />
<Button
android:id="@+id/close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="閉じる" />
</LinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment