【Android多屏适配】动态改变Listview item高度

在ListView的Adapter中去直接获取传入View的LayoutParams是会报空指针异常的,唯一的方法是在xml中嵌套布局一层LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@drawable/subject_item_bg"
    android:orientation="vertical" >
    <!-- 这层需要嵌套 -->    
    <LinearLayout
        android:id="@+id/subject_ll"
        android:layout_width="fill_parent"
        android:layout_height="120dp"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/subject_ico"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="17"
            android:layout_margin="5dp"
            android:scaleType="fitXY"
            android:src="@drawable/woji" />

        <TextView
            android:id="@+id/subject_title"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="5"
            android:layout_marginLeft="10dp"
            android:singleLine="true"
            android:text="曾经啊减肥的撒飞机 合集合集合集肥的撒飞机 合肥的撒飞机 合"
            android:textColor="#000000"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

然后再在Adapter的getView中去动态改变即可,关键代码:

if (view == null) {
                view = getActivity().getLayoutInflater().inflate(
                        R.layout.subject_list_item, null);
                holder = new ViewHolder();
                LinearLayout ll = (LinearLayout)view.findViewById(R.id.subject_ll);
                holder.tvTitle = (TextView) view
                        .findViewById(R.id.subject_title);
                holder.imgIco = (ImageView) view.findViewById(R.id.subject_ico);

                LayoutParams linearParams = (LayoutParams) ll
                        .getLayoutParams();
                linearParams.height = screenWidth * 250 / 460;
//                linearParams.gravity = Gravity.CENTER_VERTICAL;
                ll.setLayoutParams(linearParams);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }

 

posted @ 2016-08-25 12:12  星辰之力  阅读(3674)  评论(0编辑  收藏  举报