Dialog是我们做项目很常见的一项功能点了,一般的文字弹窗原生的dialog就可以帮我们实现,然而在实际开发过程中,因为弹窗布局较为复杂,充斥着各种控件,这时候原生的Dialog显然就不能满足我们的需求了,所以我们要自定义修改一番,近期正好做了些这方面的东西,也遇到了一些坑,特此整理出来!
万年不变的国际惯例——上效果图
好像丑了点,哈哈。。问题不大。
简单分析下界面,共有1个TextView文字,两个ImageView图片,两个View横竖线,画起来没啥难度
我们接下来详述实现方法。
1.先画自定义布局。
custom_share_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="分享到"
/>
<View
android:layout_width="wrap_content"
android:layout_height="1px"
android:background="#000"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/dialog_wechat"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_weight="1"
android:src="@drawable/wechat_pic" />
<View
android:layout_width="1px"
android:layout_height="match_parent"
android:background="#000"/>
<ImageView
android:id="@+id/dialog_wechatmoment"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_weight="1"
android:src="@drawable/wechatmoment_pic" />
</LinearLayout>
</LinearLayout>
2.在弹窗的入口设置方法
A、先加载自定义布局custom_share_dialog.xml
//加载自定义布局并初始化控件
AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_share_dialog, null);
ImageView wechat= view.findViewById(R.id.dialog_wechat);
ImageView wechatmoment= view.findViewById(R.id.dialog_wechatmoment);
final Dialog dialog= builder.create();
dialog.show();
Window window= dialog.getWindow();
window.setContentView(view);
//弹窗时隐藏软键盘
window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
最后一行意为在弹窗时如果软键盘处于弹出状态,此时就会隐藏掉软键盘,以防用户多次误点,特地在demo放了个EdiText以供测试。
B、此时就可以正常显示弹窗了,接下来我们对其宽高进行设置
此时根据实际需求,可以设置dialog的弹窗自适应xml布局,也可以自适应屏幕宽高比例。
//设置dialog弹窗宽高
WindowManager.LayoutParams params= window.getAttributes();
//dialog宽高适应子布局xml
params.height= LinearLayout.LayoutParams.WRAP_CONTENT;
params.width= LinearLayout.LayoutParams.MATCH_PARENT;
//dialog宽高适应屏幕
//WindowManager manager= getWindowManager();
//Display display= manager.getDefaultDisplay();
//params.height= (int) (display.getHeight()* 0.8);
//params.width= (int) (display.getWidth()* 0.5);
window.setAttributes(params);
C、接下来设置子控件的点击事件即可
wechat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
wechatmoment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
至此全部完成,没有demo的博客不是好博客,源码附上!