[英]how to loop through all buttons on a view inflated in an android service class?
我通過<action android:name="android.intent.action.MAIN" />
啟動服務類。 在onCreate()
期間,我想調用getWindow()
但是在哪里可以獲取活動引用?
您能幫我找到參考嗎?
我已經使用以下方法來膨脹一個視圖,該視圖是需要對getWindow()
進行活動引用的視圖
public class myServiceA extends Service {
public void onCreate() {
inflater1 = (LayoutInflater) this
.getSystemService(LAYOUT_INFLATER_SERVICE);
View1 = inflater1.inflate(R.layout.myview, null);
}
}
我想遍歷所有按鈕以更改視圖上的字體大小,因此我需要調用getWindow或是否存在此問題?
ViewGroup viewGroup = (ViewGroup) myActivityReference.getWindow()
.getDecorView();
第2天:經過長時間的討論,我的服務似乎沒有此類活動,因為它是從直接加載服務開始的。 我必須更詳細地更改我的問題,以便解決我想做的事情。 下面是用於格式化其他活動項目上按鈕的字體大小的代碼。 現在,要對我的服務類的視圖進行相同的處理,它將缺少活動參考。 那么,如何修改以下代碼,使其適用於服務類中的視圖?
public void setButtonFontSize(Activity myActivityReference) {
ArrayList<Button> buttons = new ArrayList<Button>();
ViewGroup viewGroup = (ViewGroup) myActivityReference.getWindow()
.getDecorView();
findButtons(viewGroup, buttons, 1);
}
private static void findButtons(ViewGroup viewGroup,
ArrayList<Button> buttons, int mode) {
for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) {
View child = viewGroup.getChildAt(i);
Button childButton;
if (child instanceof ViewGroup) {
findButtons((ViewGroup) child, buttons, mode);
} else if (child instanceof Button) {
buttons.add((Button) child);
childButton = (Button) child;
if (mode == 1)
childButton.setTextSize(12);
}
}
}
如果您希望從服務內部在屏幕上顯示視圖,則可以使用WindowManager:
public class myServiceA extends Service {
public void onCreate() {
Inflater inflater = LayoutInflater.from(this);
View view1 = inflater.inflate(R.layout.myview, null);
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(view1, params);
}
}
您還必須向清單文件添加以下權限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
更改問題的具體信息后,我得到了答案:
ViewGroup viewGroup = (ViewGroup) View1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.