自定义Dialog的小实战——根据地区选择手机号码前缀

版权声明:出于感谢(如果有收获)或对知识的尊重,未经允许禁止转载 https://blog.csdn.net/bendan50/article/details/82501817

1、Dialog设置背景透明色

dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

2、Dialog设置没有标题栏

requestWindowFeature(Window.FEATURE_NO_TITLE);

需要注意的是:该行代码的位置问题,必须在setContextView()之前执行,否则无效。

3、Dialog实例

以上图为例,思路如下:LinearLayout作为根布局,并将其背景色设为透明;然后上面addView()一个LinearLayout布局,下面addView()一个LinearLayout布局。上面的布局背景为白色且设置圆角;下面的布局背景透明、居中、添加一个图片。

简约代码如下:

LinearLayout root = new LinearLayout(mContext);
        root.setBackgroundColor(Color.WHITE);
        root.setMinimumWidth((int)(((Activity)mContext).getWindowManager().getDefaultDisplay().getWidth() * 0.8));
        root.setMinimumHeight(ResUtil.dp2px(mContext, 55));
        root.setBackgroundDrawable();//参数为一个Drawable,在此处设置圆角、边框
        LinearLayout.LayoutParams rootParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        root.setOrientation(LinearLayout.VERTICAL);
daLuRl = new RelativeLayout(mContext);
        tv1 = new TextView(mContext);
        initSonView(daLuRl,tv1,"中国大陆","+86");
        root.addView(daLuRl);
LinearLayout bottomLl = new LinearLayout(mContext);
        bottomLl.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        bottomLl.setOrientation(LinearLayout.VERTICAL);
        bottomLl.setGravity(Gravity.CENTER_HORIZONTAL);

        mCancelIv = new ImageView(mContext);
        LinearLayout.LayoutParams cancelParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        cancelParams.setMargins(0, ResUtil.dp2px(mContext, 20), 0, 0);
        mCancelIv.setLayoutParams(cancelParams);
        mCancelIv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mCancelIv.setImageResource();
        bottomLl.addView(mCancelIv);
LinearLayout rootView = new LinearLayout(mContext);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        rootView.setLayoutParams(params);
        rootView.setOrientation(LinearLayout.VERTICAL);
        rootView.setGravity(Gravity.CENTER_HORIZONTAL);

        rootView.addView(root,rootParams);
        rootView.addView(bottomLl);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(rootView);

4、弱引用的使用

private WeakReference<TextView> reference;
reference = new WeakReference<TextView>(textView);

daLuRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reference.get().setText(tv1.getText());
                dismiss();
            }
        });

猜你喜欢

转载自blog.csdn.net/bendan50/article/details/82501817