这是我的问题的 ListView 屏幕截图:
这是布局 XML:
<LinearLayout
android:id="@+id/viewer_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/background_dark"
android:orientation="vertical" >
<EditText
android:id="@+id/viewer_filter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@android:drawable/ic_menu_search"
android:hint="@string/hint_filter"
android:background="@android:color/white"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="3dp"
android:inputType="text"
android:paddingLeft="4dp"
android:selectAllOnFocus="true" >
</EditText>
<EditText
android:id="@+id/viewer_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@android:drawable/ic_menu_search"
android:hint="@string/hint_search"
android:background="@android:color/white"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="3dp"
android:layout_marginBottom="5dp"
android:inputType="text"
android:paddingLeft="4dp"
android:selectAllOnFocus="true" >
</EditText>
</LinearLayout>
<HorizontalScrollView
android:id="@+id/viewer_hscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/viewer_top" >
<ListView
android:id="@+id/viewer_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</HorizontalScrollView>
这个场景有3个问题:
- 水平滚动视图没有覆盖全屏宽度(我画了一条粗红线来标记结束)
- 水平滚动视图不水平滚动
ListView 行的宽度不均匀(这可以通过背景颜色结尾看到)(详见下面的 getView 代码)
private static final int listRowLayout = android.R.layout.activity_list_item; private Map<String, Integer> mColors = new HashMap<String, Integer>(); @Override public View getView(int position, View convertView, ViewGroup parent) { // No logs here to keep ListView performance good ViewHolder holder; int color; if( convertView == null ) { convertView = mInflater.inflate(listRowLayout, parent, false); holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(android.R.id.text1); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } String data = mData.get(position); // A compiled regex is faster than String.Contains() Matcher m = ViewHolder.regex.matcher(data); if( m.find() ) { color = mColors.get(m.group(1)); } else { color = mColors.get("V"); } holder.text.setText(data); holder.text.setBackgroundColor(color); return convertView; } private static class ViewHolder { TextView text; static Pattern regex = Pattern.compile(" ([VIDWEF])/"); }
}