[英]Android: how to add view to WindowManager, and keep it floating at the top of my app all the time?
我需要一個視圖顯示在我的應用程序的頂部,並且當它顯示時,它可以繼續顯示在我應用程序的所有其他視圖(所有片段和活動)的頂部。 它聽起來像一個浮動操作按鈕,但會始終顯示在我的應用程序的頂部。
我知道我可以通過向手機的 WindowManager 添加視圖來做到這一點,並在我退出我的應用程序時隱藏它,當我恢復我的應用程序時再次顯示它。 這種棘手的方法可以奏效,但它也需要一些額外的許可,這是我試圖避免的。
如果我只想在我的應用程序中顯示,我可以在不征得用戶額外許可的情況下實現嗎? 如果答案是肯定的,那又如何呢? 關鍵似乎是視圖的一些 LayoutParams,我試過但失敗了。
如果答案可以顯示一些詳細代碼和解釋,那就太好了。
您必須為此使用WindowManager
首先在清單中添加權限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
添加要顯示的圖像。
chatheadImg = (ImageView)chatheadView.findViewById(R.id.chathead_img);
然后進行服務並向其中添加窗口管理器。
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
只需在視圖上注冊觸摸事件
chatheadView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//To do
break;
case MotionEvent.ACTION_MOVE:
break;
});
查看這些教程以獲得更好的理解
http://www.androidhive.info/2016/11/android-floating-widget-like-facebook-chat-head/
在清單中添加此權限 windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); layoutView = layoutInflater.inflate(R.layout.ringing_layout, null);
phoneTv = layoutView.findViewById(R.id.phone);
Log.d("TAG", "showLayout: " + phoneTv );
p = new WindowManager.LayoutParams(
// Shrink the window to wrap the content rather than filling the screen
600, 600,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
PixelFormat.TRANSLUCENT);
layoutView.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
windowManager.removeView(layoutView);
}
});
p.gravity = Gravity.CENTER | Gravity.CENTER;
p.x = 0;
p.y = 0;
windowManager.addView(layoutView, p);
Log.d("TAG", "showLayout: ");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.