Android遇到的奇怪bug

作者 zheng li 日期 2016-12-24
Android遇到的奇怪bug

最近遇到一个奇怪的bug关于界面布局在RecyclerView 中显示有问题,而且和系统版本有关。
直接上代码,简化版本的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="14dp"
android:paddingRight="14dp">

<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="15dp"
android:textColor="@color/colorPrimary"
android:layout_marginTop="10dp"
android:text="position-"
android:textSize="16sp" />

<FrameLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignTop="@id/tv_title"
android:layout_alignBottom="@id/tv_title">

<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/colorAccent" />
</FrameLayout>

</RelativeLayout>

显示效果如图
正常效果图

将这个布局用在RecyclerView

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_list_item,parent,false));
}

android6.0上显示效果如下
android6.0正常列表
效果正常,但是通用的代码在 android 4.4 上却显示成这样

android4.4不正常列表
显示不出左边的竖线了!!
这里使用的版本是compile 'com.android.support:recyclerview-v7:24.2.1'

因为我一直用的6.0的手机测试,并没有发现这个问题,直到测试在4.4的手机上运行时才发现这个问题。

非常奇怪的问题,暂时没有深究,猜猜可能与layout_alignTop layout_alignBottom 有关.
要在4.4的中使用如下代码就可以正常显示了

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout=new LinearLayout(parent.getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_list_item,parent,false),LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
return new ViewHolder(linearLayout);
}

当然,也有可能是竖线View的问题,下面这样布局也可以的

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="14dp"
android:paddingRight="14dp">

<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:text="position-"
android:textColor="@color/colorPrimary"
android:textSize="16sp" />

<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignBottom="@id/tv_title"
android:layout_alignTop="@id/tv_title"
android:background="@color/colorAccent" />

</RelativeLayout>

有空再深入研究下RelativeLayout.