我正在开发一个Android应用程序.我希望能够通过代码添加一个视图,该视图是在应用程序的所有活动之上绘制的.
我试图将它添加到窗口管理器:
LayoutInflater inflater = activity.getLayoutInflater();
layout = inflater.inflate(R.layout.toast_layout, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.gravity = Gravity.BOTTOM;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
final WindowManager mWindowManager = (WindowManager);
activity.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mWindowManager.addView(layout, params);
Run Code Online (Sandbox Code Playgroud)
但是,像这样添加它我面临两个问题:
1.当我退出应用程序时,仍会显示布局.
2.布局不响应Click事件.
有没有其他解决方案来实现这一目标
谢谢.
1)创建扩展Activity的BaseActivity.
2)现在,您的所有活动应该扩展BaseActivity而不是Activity
3)重写setContentView()方法.
4)在此方法中创建空白垂直linearLayout.
5)在此布局中添加topView
6)然后在此线性布局中添加膨胀视图
7)最后调用super.setContentView(passLinearLayoutHere)
如何实施?
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
public class BaseActivity extends Activity {
@Override
public void setContentView(int resId) {
LinearLayout screenRootView = new LinearLayout(this);
screenRootView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
screenRootView.setOrientation(LinearLayout.VERTICAL);
// Create your top view here
View topView = new View(this); // Replace this topview with your view
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View screenView = inflater.inflate(resId, null);
topView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//You will get onclick here of your topview in whatever screen it is clicked
}
});
screenRootView.addView(topView);
screenRootView.addView(screenView);
super.setContentView(screenRootView);
}
}
Run Code Online (Sandbox Code Playgroud)
将LayoutParams类型更改TYPE_TOAST为TYPE_APPLICATION,并删除我建议的先前标志,
并BaseActivity为您的应用中的所有活动创建一个,在该活动中onResume()添加此视图,WindowManager并onPause()删除该视图,如,
windowManager.removeView(view);
Run Code Online (Sandbox Code Playgroud)
为了管理视图的显示/视图,我使用了 Gopal 提出的解决方案。我附加了 onStop 和 onResume 事件,以便在退出应用程序时隐藏视图。
对于点击事件,我意识到 toast 类型不响应点击事件。因此我改变了类型
params.type = WindowManager.LayoutParams.TYPE_TOAST;
Run Code Online (Sandbox Code Playgroud)
到
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
Run Code Online (Sandbox Code Playgroud)
我也必须添加以下权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12945 次 |
| 最近记录: |