android webview内容压线问题解决方法

最近在使用webview做页面开发,项目上要求webview在获取到焦点的时候需要有边框线,于是添加上了webview的选中效果,但是出现了网页中的内容压选中框的情况。之后给webview添加padding也不能解决这个问题,从网上搜索后发现,webview设置padding是不会起作用的,这个是webview的一个bug。但是问题还是地解决的,于是想了如下的webview选中的替代方案:

  1. webview设置背景色为透明色
  2. 在webview下方放一个LinearLayout里面有个ImageView,大小刚好比webview大出一个边框
  3. 当webview获取到焦点的时候,显示有边框的ImageView,当webview失去焦点的时候,显示正常的无边框的ImageView。

下面贴出代码:

1.xml文件配置(LinearLayout在webview下面并且比其大4dp)

<LinearLayout 
        android:id="@+id/web_linerlayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="2dp"
        android:layout_alignParentBottom="true"
	    android:layout_below="@+id/title_Relay"
	    android:layout_toRightOf="@id/btn"
	    android:layout_marginTop="5dp"
        android:layout_marginRight="8dp"
        android:background="@color/3C123456"
        android:padding="0dp">
    </LinearLayout>
    <WebView
        android:id="@+id/web_WebView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="6dp"
        android:layout_alignParentBottom="true"
	    android:layout_below="@+id/title_Relay"
	    android:layout_toRightOf="@id/btn"
	    android:layout_marginTop="9dp"
        android:layout_marginRight="11dp"
        android:layout_marginBottom="4dp"
        android:layerType="software"        
        android:hardwareAccelerated="true">
   	</WebView>


2.JAVA代码

final LinearLayout linearlayout = (LinearLayout)findViewById(R.id.web_linerlayout);
		final ImageView imageView = new ImageView(MainActivity.this);
		imageView.setImageResource(R.drawable.webview_select);
		LayoutParams layoutParams = new LayoutParams(linearlayout.getLayoutParams().width, linearlayout.getLayoutParams().height);
		imageView.setLayoutParams(layoutParams);
		linearlayout.addView(imageView);
		
		WebView shopWeb = (WebView) findViewById(R.id.web_WebView);
		shopWeb.setOnFocusChangeListener(new View.OnFocusChangeListener() 
		public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					linearlayout.removeView(imageView);
				}else{
					linearlayout.addView(imageView);
				}
			}
		});




原文地址:https://www.cnblogs.com/suncoolcat/p/3292278.html