gpt4 book ai didi

android - 在所有 Activity 之上添加一个 View

转载 作者:IT老高 更新时间:2023-10-28 23:33:06 28 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序。我希望能够通过代码添加一个 View ,该 View 绘制在应用程序的所有 Activity 之上。

我已经尝试将它添加到窗口管理器:

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);

但是,像这样添加它我面临两个问题:

1.当我退出我的应用程序时,布局仍然显示。

2.布局不响应点击事件。

还有其他解决方案可以实现这一点吗?

谢谢。

最佳答案

1) 创建扩展Activity的BaseActivity。

2) 现在您的所有 Activity 都应该扩展 BaseActivity 而不是 Activity

3) 重写 setContentView() 方法。

4) 在此方法中创建空白的垂直线性布局。

5) 在此布局中添加您的 topView

6) 然后在这个线性布局中添加膨胀 View

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);
}

}

关于android - 在所有 Activity 之上添加一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976701/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com