Android自定义圆角对话框

自定义对话框MyDialog类继承Dialog类:

package com.example.jjy.myapplication; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by jjy on 16-5-15. */ public class MyDialog extends Dialog{ private Button positiveButton, negativeButton; private TextView contenttv; public MyDialog(Context context) { super(context,R.style.mydialog); View view = LayoutInflater.from(getContext()).inflate(R.layout.mydialoglayout, null); //通过LayoutInflater获取布局 contenttv = (TextView) view.findViewById(R.id.title); positiveButton = (Button) view.findViewById(R.id.acceptbtn); negativeButton = (Button) view.findViewById(R.id.refusebtn); setContentView(view); //设置view } //设置内容 public void setContent(String content) { contenttv.setText(content); } //确定按钮监听 public void setOnPositiveListener(View.OnClickListener listener){ positiveButton.setOnClickListener(listener); }//否定按钮监听 public void setOnNegativeListener(View.OnClickListener listener){ negativeButton.setOnClickListener(listener); } }


R.style.mydialog 对话框属性在 values/styles.xml中设置:

@android:color/transparenttruetrue




R.layout.mydialoglayout 布局文件:



其中对话框的圆角背景mydialogshape:



最后在Activity中调用:

package com.example.jjy.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MyDialog myDialog=new MyDialog(MainActivity.this); myDialog.getWindow().setLayout(800,450); //对话框大小应根据屏幕大小调整 myDialog.setContent("自定义对话框"); myDialog.setOnPositiveListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"YES", Toast.LENGTH_SHORT).show(); } }); myDialog.setOnNegativeListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this,"NO",Toast.LENGTH_SHORT).show(); } }); myDialog.show(); } }); } }

结果截图: 【Android自定义圆角对话框】
Android自定义圆角对话框
文章图片


    推荐阅读