- 还记得几年前做安卓开发实习生,开发的第一个功能就是签到弹窗。目前,弹窗都使用DialogFragment了,但是脑海中一直有一个疑问,为啥就不能直接重写Dialog了?亲自动手实践了一下,发现用Dialog也不麻烦。
- 看设计稿和Demo效果,时间问题,Demo只实现了一部分。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CenterInScreenDialog dialog = new CenterInScreenDialog(MainActivity.this,R.layout.my_dialog);
dialog.show();
}
}
- CenterInScreenDialog代码
public class CenterInScreenDialog extends Dialog {
View view;
public CenterInScreenDialog(Context context, int layoutId) {
super(context);
view = View.inflate(context, layoutId, new LinearLayout(context));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_NO_TITLE);//去除标题
super.onCreate(savedInstanceState);
if (view != null) {
setContentView(view);
}
}
@Override
protected void onStart() {
super.onStart();
getWindow().setBackgroundDrawableResource(android.R.color.transparent); //去除自带的背景
}
}
弹窗布局文件:my_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="#000000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<RelativeLayout
android:id="@+id/rl"
android:layout_width="313dp"
android:layout_height="213dp"
android:layout_centerHorizontal="true"
android:background="@drawable/dialog_bg">
</RelativeLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/rl"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:src="@drawable/close" />
</RelativeLayout>
</RelativeLayout>
圆角背景文件:drawable文件夹下的dialog_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="15dp"/>
<solid android:color="#FFFFFF"/>
</shape>