您的位置:首页 > 运维架构

PopupWindow实现弹窗,可以任意自定义布局

2016-09-18 22:59 288 查看
用于实现弹窗,可以任意自定义布局,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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐