我使用bindView()
方法是自定义CursorAdapter
实现,以动态地将文本视图添加到列表中。
每个列表项都由list_item
布局表示,其中包含来自Android Flowlayout的flow_layout
布局
<!--List Item Layout-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#FFFFFF">
<!--Flow Layout-->
<org.apmem.tools.layouts.FlowLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/view_padding"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:id="@+id/hash_tag_layout"
>
</org.apmem.tools.layouts.FlowLayout>
</LinearLayout>
每个flow_layout
实例添加到list item
的文本视图数反映了游标中返回的行值数。
public void bindView(View view, Context context, Cursor cursor) {
// Flow layout wraps new views around the screen.
FlowLayout flowLayout = (FlowLayout) view.findViewById(R.id.flow_Layout);
// getRowValues() puts row values from cursor into an array list.
ArrayList<> rowValues = getRowValues(cursor);
// A new text view is created and inserted into Flow layout
// for each value in rowValues
TextView tv;
for value in rowValues {
tv = = new TextView(ctx);
tv.setText(value);
flowLayout.addView(tv);
}
}
要重新迭代,我希望每个flow_layout
实例的每个list_item
内的文本视图数量反映光标返回的行值的数量。
但是,每次重新滚动列表项时,该特定项目中的文本视图数量会翻倍,而另外,绑定数据有时会在光标位置和列表项位置之间进行对称反映。我认为问题与旧文本视图的回收有关。如何防止新文本视图堆叠到旧文本视图上?
以下是自定义游标适配器
的完整实现public class DatabaseAdapter extends CursorAdapter {
Context ctx;
public DatabaseAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
ctx = context;
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
return v;
}
public void bindView(View view, Context context, Cursor cursor) {
// Flow layout wraps new views around the screen.
FlowLayout flowLayout = (FlowLayout) view.findViewById(R.id.flow_Layout);
// getRowValues() puts row values from cursor into an array list.
ArrayList<> rowValues = getRowValues(cursor);
// A new text view is created and inserted into Flow layout
// for each value in rowValues array list
TextView tv;
for value in rowValues {
tv = = new TextView(ctx);
tv.setText(value);
flowLayout.addView(tv);
}
}
}
答案 0 :(得分:1)
if(LinearLayout.getChildCount() > 0)
LinearLayout.removeAllViews();
答案 1 :(得分:0)
在您的LinearLayout
中,您必须已添加TextView
,标识为tv1
。
然后代替:
TextView tv1 = new TextView();
这样做:
LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear_layout);
TextView tv1 = layout.findViewById(R.id.tv1);
tv1.setText(Title);