前言
本文主要給大家介紹了如何更改Dialog的標題與按鈕顏色的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
android.support.v7.app.AlertDialog
在這個類中第一行就定義了如下變量:
final AlertController mAlert;
AlertDialog的功能的具體實現都在這個AlertController內部封裝.
修改按鈕顏色
1. AlertDialog.getButton
public Button getButton(int whichButton) { return mAlert.getButton(whichButton); }這里的參數whichButton有三種類型:
傳入對應的參數即可得到對應的Button
Button btnPositive = (Button)AlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);btnPositive.setTextColor(color);
這種方式只能設置按鈕的顏色,而無法設置標題顏色
2 AlertDialog.getWindow
AlertDialog的構造函數如下:
protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) { super(context, resolveDialogTheme(context, themeResId)); mAlert = new AlertController(getContext(), this, getWindow()); } 這里初始化了AlertController,并傳入了getWindow() ,這個getWindow()是AlertDialog繼承自Dialog的方法.方法如下:
#Dialog.getWindow() public @Nullable Window getWindow() { return mWindow; } 將這個window對象傳入AlertController后,在AlertController源碼中可以看到對話框標題和按鈕的id,并通過Window.findViewById(id)獲取對應的View.
所以這里可以這樣得到對話框的標題和按鈕:
//標題TextView tvTitle = (TextView)AlertDialog.getWindow().findViewById(R.id.alertTitle);//按鈕Button btnPositive = (Button)AlertDialog.getWindow().findViewById(R.id.button1);
然后設置所需要的顏色就可以了.這種方法可以修改Dialog的所有設置了id的控件的字體顏色.
3 反射
3.1 首先拿到AlertController對象
Field mAlert = AlertDialog.class.getDeclaredField("mAlert"); mAlert.setAccessible(true); Object controller = mAlert.get(dialog);在AlertController內部查找到需要更改字體顏色的標題和按鈕
Button mButtonPositive;Button mButtonNegative;Button mButtonNeutral;private TextView mTitleView;private TextView mMessageView;
然后通過反射獲取對應控件,修改控件顏色即可
Field mTitleView = controller.getClass().getDeclaredField("mTitleView"); mTitleView.setAccessible(true); TextView tvTitle = (TextView) mTitleView.get(controller); tvTitle.setTextColor(Color.GREEN);//更改標題的顏色三種方式比較起來,第二種是最簡單,效率也是最高的
更改Dialog顯示的位置
Window window = dialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes();lp.gravity = Gravity.BOTTOM;lp.x = 100;lp.y = 100;window.setAttributes(lp);
這里要注意的是,WindowManager.LayoutParams的x和y坐標,看源碼注釋如下:
/** * X position for this window. With the default gravity it is ignored. * When using {@link Gravity#LEFT} or {@link Gravity#START} or {@link Gravity#RIGHT} or * {@link Gravity#END} it provides an offset from the given edge. */ @ViewDebug.ExportedProperty public int x; /** * Y position for this window. With the default gravity it is ignored. * When using {@link Gravity#TOP} or {@link Gravity#BOTTOM} it provides * an offset from the given edge. */ @ViewDebug.ExportedProperty public int y; 如果lp.gravity是默認的,那么x和y即使設置了也是無效的.因此x和y需要和lp.gravity搭配使用才有效果.當然lp.gravity也可以單獨使用.
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答