简体   繁体   English

以编程方式在AlertDialog中自定义按钮

[英]Custom button in AlertDialog programmatically

After lots of research on stackoverflow and google, I have really found no issue to my problem. 经过大量关于stackoverflow和google的研究,我真的发现我的问题没有问题。 Well, I'd like to create a button with height = 50 and width = 50 on top right of my dialog. 好吧,我想在对话框的右上方创建一个高度为50且宽度为50的按钮。 Well, I can set height without problem, but width doesn't work. 好吧,我可以毫无问题地设置高度,但是宽度不起作用。 I tried with creating a linearLayout, but params never took in consideration. 我尝试创建linearLayout,但从未考虑过参数。 Here is my code (height is sets properly) : 这是我的代码(高度设置正确):

private void hello(){
    Button button = new Button(this);

    button.setMinimumWidth(0);
    button.setWidth(50);
    button.setMinimumHeight(0);
    button.setHeight(50);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v){
            sayHello();
        }
    });

    new AlertDialog.Builder(this) 
            .setTitle("Hello world")
            .setView(button)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                    Toast.makeText(getApplicationContext(), "Click !", 
                    Toast.LENGTH_SHORT).show();
                    hello();
                }
            })

            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton){
                }
            })
            .show();
}

I tried with : 我尝试了:

        button.setLayoutParams(new LinearLayout.LayoutParams(50, 50));

Without any success. 没有任何成功。

And with : 与 :

LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT);
    rlp.height = 50;
    rlp.width = 50;

    button.setText("i");
    button.setLayoutParams(rlp);

And doesn't work either... 而且也不起作用...

I really don't understand what's happening, can you try help me please? 我真的不明白发生了什么,请您能帮我吗?

I precise, I don't have any xml, it's only in java. 我精确地说,我没有任何xml,仅在Java中。

I finally decided to create my own alert dialog to customize it as I wish. 我最终决定创建自己的警报对话框,以根据需要对其进行自定义。 I had to create a xml file and used an inflater. 我必须创建一个xml文件并使用充气机。 The reason why setHeight works and not setWidth will forever stays a mystery... setHeight起作用而不是setWidth起作用的原因将永远是个谜...

Thank's for your help anyway 还是要谢谢你的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM