1. 程式人生 > >PopupWindow實現彈窗,可以任意自定義佈局

PopupWindow實現彈窗,可以任意自定義佈局

用於實現彈窗,可以任意自定義佈局,android中彈窗可以分為AlertDialog和popupWindow,AlertDialog只能顯示固定在中間位置,popupWindow可以在任意位置,相對更加靈活。

1.主佈局設定

<Button
        android:id="@+id/button_submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="提交"
        android:textSize="20sp"
android:onClick="submitClick"/>

2.自定義彈窗佈局

<Button
        android:id="@+id/button_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新"
        android:textSize="20sp"
        android:layout_weight="1"/>
    <Button
        android:id
="@+id/button_delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刪除" android:textSize="20sp" android:layout_weight="1"/>

3.程式碼實現
//為彈窗提供自定義的佈局
//建立彈窗PopupWindow
//設定相關的屬性
//顯示彈窗

private View button_update;
    private
View button_delete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } //點選button事件 public void submitClick(View view){ showSubmitClick(view); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void showSubmitClick(View view) { View v=getLayoutInflater().inflate(R.layout.popup_window,null); //載入的佈局 button_update = v.findViewById(R.id.button_update); button_delete = v.findViewById(R.id.button_delete); //建立彈窗popupwindow PopupWindow popupWindow =new PopupWindow(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,true); //設定背景 popupWindow.setBackgroundDrawable(getDrawable(R.mipmap.index_intro_bg)); BitmapDrawable bitmapDrawable =new BitmapDrawable(getResources(), BitmapFactory.decodeResource(getResources(),R.mipmap.index_intro_bg)); //設定透明度 popupWindow.getBackground().setAlpha(80); //設定動畫效果 popupWindow.setAnimationStyle(android.R.anim.fade_in); //設定點選彈窗外面消失 popupWindow.setOutsideTouchable(true); //設定防止軟鍵盤遮擋popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED); //顯示彈窗 popupWindow.showAsDropDown(view); //設定點選事件 button_delete.setOnClickListener(this); button_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show(); } }); } @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "刪除成功", Toast.LENGTH_SHORT).show(); }