自定义Dialog

说明

此文模仿
http://www.jianshu.com/p/68dc2d15537e,结合了自身需求更改了部分内容

自定义Dialog三部曲

  1. 编写自定义布局
  2. 自定义一个类并继承AlertDialog
  3. 实现调用环节

自定义布局

自定义Dialog_第1张图片
image
  • 系统自带的dialog是无法实现该效果的,所以需要使用自定义Dialog
  • 这里只需要按正常的布局实现即可
    
        
    
    
        
  • 这里的代码主要为了展示我们只需要很正常的布局即可,删掉了大部分没有意义的代码

自定义一个类并继承AlertDialog

public class MyAlertDialog extends AlertDialog implements View.OnClickListener{
    private Context mContext;
    private Button item1Btn;
    private Button item2Btn;
    private Button item3Btn;
    public MyAlertDialog(Context context){//构造类,这里注意一定要public
        super(context);
        mContext= context;
    }
    @Override
    protected void onCreate(Bundle savedInstancesState){
        super.onCreate(savedInstancesState);
        setContentView(R.layout.view_dialog);
        initView();
        initDate();
    }
    private void initView(){//初始化视图
        GoodBtn= (Button) findViewById(R.id.Dialog_Button_good);
        NormalBtn= (Button) findViewById(R.id.Dialog_Button_normal);
        BadBtn= (Button) findViewById(R.id.Dialog_Button_bad);
    }
    private void initDate(){//注册监听器
        GoodBtn.setOnClickListener(this);
        NormalBtn.setOnClickListener(this);
        BadBtn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.Dialog_Button_good:
                break;
            case R.id.Dialog_Button_normal:
                break;
            case R.id.Dialog_Button_bad:
                break;
            default:
                break;
        }
    }
}

实现调用环节

  • 在调用的地方实例化,并调用show()展示
MyAlertDialog myAlertDialog=new MyAlertDialog(MainActivtiy.this);
myAlertDialog.show();
  • 实际
public class MainActivity extends AutoLayoutActivity {
    private Button test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test= (Button) findViewById(R.id.Button_test);
        test.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                MyAlertDialog myAlertDialog=new MyAlertDialog(MainActivity.this);
                myAlertDialog.show();
            }
        });
    }

}

你可能感兴趣的:(自定义Dialog)