前言:这篇文章是有关对话框的最后一篇了,最近工作是很忙,不过闲下来的时候也不想写博客,估计是累过头了,还好以前定了个任务,每个月必须写四篇,这才强制自己去一直更新,马总说过,梦想这东西还是要有的,万一实现了呢,趁在阿里的两年,努力!
相关文章:
1、《详解Dialog(一)——基础元素构建》
2、《详解Dialog(二)——有关列表的构建》
3、《详解Dialog(三)——自定义对话框视图及参数传递》
今天给大家讲讲有关自定义对话框的相关内容,前面两篇都在在利用系统提供的函数来实现对话框,但局限性太大,当我们想自己定义视图的时候,就不能利用系统函数了,就需要我们这里的自定义对话框了,有关自定义对话框的东东,以前有写过一篇《android之Dialog相关》,写的不好,今天给大家重新写一篇
一、雏形构建
先给大家看下这小节的效果图:
自定义一个对话框,内容是四个ImageView横排;
1、Dialog布局
根据上图的对话框样式,我们看一下Dialog的布局定义(custom_dialog.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/log_in_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="match_parent"
android:layout_height="100dip"
android:src="@drawable/animal1"
android:clickable="true"
android:layout_weight="1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dip"
android:src="@drawable/animal2"
android:clickable="true"
android:layout_weight="1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dip"
android:src="@drawable/animal3"
android:clickable="true"
android:layout_weight="1"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="100dip"
android:src="@drawable/animal4"
android:clickable="true"
android:layout_weight="1"/>
</LinearLayout>
2、从Dialog派生对话框类
有关构造函数:
有三种构造函数,现在我这里使用重写了两个,这里只需要使用第一个,即传进去context即可;
有关OnCreate()
在OnCreate()时,利用LayoutInflater获取我们对话框的View,然后利用SetContentView指定为我们CustomDialog类的布局。
public class CustomDialog extends Dialog {
Context mContext;
public CustomDialog (Context context){
super(context);
mContext = context;
}
public CustomDialog(Context context, int theme) {
super(context, theme);
mContext = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
this.setContentView(layout);
}
}
3、主函数(MainActivity)
在MainActivity中,我们写一个Button,当用户点击的时候弹出我们自定义的对话框实例
MainActivity的布局:(activity_main.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"