如何为Android webview设置边框

Miu*_*nga 14 android android-webview

在我的程序中,当按钮单击时,webview将以单独的布局加载.该布局只有该Web视图.我想为此添加边框.我将以下单独的XML添加到该webview的后台但不起作用.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke android:width="10dp" android:color="#000000" />
<padding android:left="2dp" android:top="2dp" android:right="2dp"android:bottom="2dp"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

如何在Android中为webview添加边框..?谢谢

Abh*_*nda 25

将WebView包含在布局中,将边框添加到布局,并在布局中保留2dp的填充.


Jam*_*mey 5

Abhinav 的回答是正确的,我只是为像我这样遇到这个答案甚至还不知道如何“将 WebView 包含在布局中”或“向布局添加边框”的绝对初学者添加这些附加信息;希望它可以帮助某人:

  1. 在下面创建一个新目录/res并为其命名drawable(您已经拥有drawable-hdpidrawable-mdpi等;这些用于不同的分辨率——drawable无论分辨率如何,都将使用这个新目录)。
  2. 在 下创建一个新的 XML 文件drawable并命名border.xml(在 Android Studio 中,您可以右键单击该drawable目录并单击 New>Drawable Resource File)。
  3. 将 miuranga 的 XML 的全部内容粘贴到border.xml并保存。这称为“可绘制资源”,将在下一步中拉入您的布局文件中。
  4. 在您的布局文件中,围绕 WebView 创建一个新布局,就像我对子 LinearLayout 所做的那样,如下所示。请注意, LinearLayout 检索属性android:background设置为的可绘制资源@drawable/border。我相信它是border.xml通过文件名减去扩展名来检索的。通过将边框添加到包围 WebView 的 Layout,您可以在视觉上实现 Webview 周围的边框,效果很好。

activity_main.xml 内容:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.test.app.MainActivity"
   android:orientation="vertical">
<LinearLayout android:background="@drawable/border"
                  android:layout_width="match_parent"
                  android:layout_height="380px">
    <WebView xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@+id/webview"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />
     </LinearLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)