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