Android App:使用对话框片段中的自定义背景替换默认按钮背景 [英] Android App: Replace default button background with custom background in a Dialog Fragment
问题描述
我想做的是更改我编写的自定义DialogFragment的默认背景.通常,我会通过更改XML布局文件来完成此操作,但是,对于DialogFragment,这些按钮在布局文件中不存在.
What I'm trying to do is change the default backgrounds of a custom DialogFragment that I have written. Normally, I would do this by changing the XML layout file, however, for a DialogFragment these buttons don't exist in the layout file.
本质上,我试图访问setPositiveButton,setNegativeButton和setNeutral按钮以对其进行修改.另外,我接下来将尝试通过id获得它们,但是,由于它们不是在布局文件中定义的,因此我没有相应的id.我已经找到了许多有关如何修改其余布局的示例,但是在任何地方都找不到可以修改正/中性/负按钮的地方.
In essence, I'm trying to get access to the setPositiveButton, setNegativeButton and setNeutral buttons in order to modify them. Alternatively, I would next try to do this by getting them by id, however, since they aren't defined in a layout file, I do not have a corresponding id for them. I've found plenty examples of how to modify the rest of the layout, but I can't find anywhere that positive/neutral/negative buttons are modifiable.
理想情况下,我可以在下面的代码块中做到这一点:
Ideally, I could do this in the following block of code:
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
})
谢谢.
推荐答案
此处是代码...按钮实例仅在创建对话框之后才有效.希望这对您有所帮助.
Here is the code ... The button instance is valid only after the dialog created. Hope this helps you.
public static class CustomDialog extends DialogFragment
{
public static CustomDialog newInstance()
{
return new CustomDialog();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
super.onCreateDialog(savedInstanceState);
Builder builder = new AlertDialog.Builder(getActivity());
AlertDialog dialog = builder.create();
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL",new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return dialog;
}
@Override
public void onStart()
{
super.onStart();
Button pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
Button nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(R.color.Blue));
nButton.setBackgroundColor(getResources().getColor(R.color.Green));
}
}
这篇关于Android App:使用对话框片段中的自定义背景替换默认按钮背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!