Android 3.2 - 在 DialogFragment 中自定义 AlertDialog 按钮

标签 android android-layout android-widget android-button android-dialogfragment

我创建了一个扩展 DialogFragment 的类,它在它的 onCreateDialog 方法中返回一个 AlertDialog,例如 here .
问题是,我想增加标准(正)按钮的高度,但我无法捕获它来改变它的高度。
当我在 DialogFragment

的 onCreateDialog 方法中执行以下操作时
mAlertDialog = new AlertDialog.Builder(getActivity())
            .setView(messageView)
            .setCustomTitle(titleView)
            .setPositiveButton(R.string.dialog_button,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((ContextSwapUserInterface) getActivity()).instructionsAccepted();
                    }
                }
            )
            .create();

mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setHeight(60);

我收到一个异常,显示“...无法实例化 ComponentInfo...”
我想这是因为此时 Button 没有正确实例化。
因此,在我创建 DialogFragment 并调用它的 .show 方法之后,我尝试在我的主要 Activity 中获取按钮:

// Create and show a new InstructionsDialogFragment
DialogFragment instructionsDialogFragment = InstructionsDialogFragment.newInstance(mInstructions);
instructionsDialogFragment.show(getFragmentManager(), "Instructions Dialog");
((Button) instructionsDialogFragment.getDialog().findViewById(android.R.id.button1)).setHeight(60);

我还尝试了以下,而不是上面的最后一行:

((AlertDialog) instructionsDialogFragment.getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setHeight(60);

两个版本都会导致 NullPointerException。在使用 DialogFragment 时,是否有任何简单的方法来自定义 AlertDialog 的按钮?

最佳答案

好的 - 尝试在 fragment 的 onActivityCreated 方法中获取按钮。我为 listfragment 做了这个,但它应该做同样的事情 - 检查你有正确的 ID 等。

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Button b = (Button)this.getView().findViewById(R.id.buttonID);

        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Button Clicked",  Toast.LENGTH_SHORT).show();
            }
    });

关于Android 3.2 - 在 DialogFragment 中自定义 AlertDialog 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10581944/

相关文章:

android - android中的局域网调用

Android - 网格布局和交错网格布局之间的区别

android - 按下按钮时如何更改文本颜色?

Android:在密度相同但尺寸不同的屏幕上拟合图像

android-layout - Android选项菜单 - 单行中的多个项目

java - 如何更改小部件启动器预览?

android - 在内存不足的情况下让 AsyncTask 保持 Activity 状态?

android - Android 的外部 SDCard 文件路径

android 如何停止 mHandler.postDelayed

android - 两次通过 UI 布局 : Why?