【发布时间】:2021-03-29 12:53:24
【问题描述】:
我是 Android 开发的新手,我正在研究现有的代码库。
我有一个android.webkit.WebView 实例,我需要在其右下角添加一个按钮。而且我还需要按钮保持固定。我不希望它随着 webview 的内容滚动。我希望按钮始终位于 webview 本身的右下角,而不是其内容。
为此,我扩展了 WebViewClient 类并覆盖了onPageStarted 方法,这就是我正在考虑添加代码以添加按钮的地方。
我的代码如下所示:
public class MyWebViewClient extends WebViewClient {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//TODO: create a Button instance here and place it on top of the webview
}
}
为了创建和添加按钮,我尝试了以下不同的选项,但它们都没有像我想要的那样工作。它们都以 webview 最左上角的按钮结束(在 webview 坐标系中的坐标 (0,0) 处),并且当 webview 滚动时,按钮会随着内容滚动。
@Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
super.onPageStarted(webview, url, favicon);
//TODO: create a Button instance here and place it on top of the webview
Button button = new Button(webview.getContext());
button.setText("35");
RelativeLayout.LayoutParams layoutParams = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.width = 44;
layoutParams.height = 44;
layoutParams.rightMargin = 20;
layoutParams.bottomMargin = 20;
button.setLayoutParams(layoutParams);
webview.addView(button);
}
我也尝试过使用 LinearLayout,但这导致了类似的行为,即按钮位于 Web 视图的顶部,并且按钮随着 Web 视图的内容滚动。
我一直在努力寻找答案,似乎 FrameLayout 也可能是一种方法,但假设这是正确的,我不确定我是否需要这样做 webview.setLayoutParams(new FrameLayout(...)) 或者是否需要这样做而是应用于按钮,还是需要同时设置?
回顾一下,我正在尝试在 Web 视图顶部添加一个按钮,以便:
- 它位于 Web 视图的右下角。
- 它不会随着 Web 视图的内容滚动。无论网页视图是否滚动,它都应该固定在同一个右下角位置。
我的问题是:最好的方法是什么(如果可能,以编程方式,而不是使用 XML)。我应该使用 FrameLayout 还是其他东西?
【问题讨论】:
标签: android android-layout webview android-framelayout