I have a ListView with a custom Adapter that creates rows containing TextViews that may have 1 or 2 lines of text.
news_row.xml:
<?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="fill_parent"
android:orientation="horizontal">
<TextView android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="48dip"
android:padding="6dp"
android:textSize="14sp">
</TextView>
</LinearLayout>
The Adapter:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_row, null);
}
else {
TextView titleView = (TextView)convertView.findViewById(R.id.text);
System.out.println(titleView.getText() + " to **" +
stories.get(position).title);
}
TextView titleView = (TextView)convertView.findViewById(R.id.text);
titleView.setText(stories.get(position).title);
titleView.setGravity(Gravity.CENTER_VERTICAL);
开发者_Python百科 return convertView;
}
After scrolling, some single-line TextViews appear aligned to the top of the row, and some 2 line TextViews are at the bottom of the row. The problem seems to happen when a row that originally contained a 2 line TextView is given a single line of text, and vice-versa.
I had thought that setting Gravity in getView would fix this row recycling problem but it must be something else. What if I create the TextView programmatically each time the row is recycled? Is that what it takes to "reset" it?
The row views are re-used in the listView. the first ten(I guess 10 or may be less) are inflated the first time and the size/gravity etc are set. When the users scrolls below the visible rows the top row is recycled and fed to the next upcoming row. Thus the view for the top most row is reused for the next upcoming row. If your top row and next upcoming row have different number of lines, the behavior you are seeing is expected.
Solution. Set the text gravity and number of lines during initial inflate, all your rows will be of same size regardless of number of lines in them. You should no longer see the fluctuation you are observing.
See this explanation for more details http://android.amberfog.com/?p=296
The solution was to set the textView number of lines (as Veeresh said) but not during initial inflate.
titleView.setLines(2);
Not exactly satisfactory (what if I have n
lines?) and it doesn't even make sense considering that the height of the textView is already set explicitly in the layout file. Oh well.
精彩评论