Android中popupwindow使用方法
建立彈窗後,調用這個彈窗即可。
首先建立一個XML檔案:
例如:popup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="26sp"
android:text="觸發事件1"
/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="26sp"
android:text="觸發事件2"
/>
</LinearLayout>
這個是彈窗的内容。可以看到,定義了2個按鈕。分别觸發兩個事件。
接着在類中新定義一個popupwindow的方法:
private void showPopupWindow(View view){
View contentView = LayoutInflater.from(mContext).inflate(R.layout.changephoto, null);
// 設定按鈕的點選事件
Button button1 = (Button) contentView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//觸發事件1
}
});
Button button2 = (Button) contentView.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//觸發事件2
}
});
final PopupWindow popupWindow = new PopupWindow(contentView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupWindow.setTouchable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
// 設定好參數之後再show
popupWindow.showAsDropDown(view);
}
接下來在需要的地方直接調用showPopupWindow()。注意往裡傳入View。
例如某個代碼片段,按鈕點選:
@Override
public void onClick(View v) {
showPopupWindow(v);
}