【发布时间】:2015-11-16 15:09:15
【问题描述】:
我需要创建一个包含不同宽度和颜色的矩形列表的布局。所以我决定创建一个自定义视图,它绘制一个矩形并创建CursorAdapter 的子类,它将用我的矩形填充ListView,并使用来自Cursor 的数据设置它们的大小和颜色。
我尝试在newView() 方法中创建视图并将其添加到root,但它不起作用。
我需要创建一些布局并在newView() 中填充它吗?我应该如何设置矩形的大小和颜色?
我阅读了this answer,它与我的问题没有任何共同之处。请先阅读问题,然后再将其标记为已回答。
更新
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//View is created programmatically
//Set color depending on context type.
View view = LayoutInflater.from(context).inflate(R.layout.record_item_layout, parent, false);
Log.i(LOG_TAG, "(newView)new view have been created");
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Log.i(LOG_TAG, "(bindView) binding to out view");
int colorId = cursor.getInt(cursor.getColumnIndex(TrackerContract.UserRecordsEntry.COLUMN_CONTEXT_ID));
RecordView recordView = (RecordView) view;
//These layout params we need to set height to MAX, and width depending on record duration.
recordView.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT));
recordView.setColorId(colorId);
recordView.invalidate();
//do something?
}
<?xml version="1.0" encoding="utf-8"?>
<mypackage.RecordView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="@+id/record_view"
custom:colorId="5"/>
【问题讨论】:
-
我们需要看一些代码。
-
另外,请详细解释一下“它不工作”是什么意思。请记住,
newView()中的 您不会“将其添加到根目录” --ListView负责执行此操作。 “我需要创建一些布局并在 newView() 中对其进行扩展吗?” ——大概。 “我应该如何设置矩形的大小和颜色?” -- 在bindView()中执行此操作 -
取决于您的需求,但
SimpleCursorAdapter+SimpleCursorAdapter.ViewBinder在常见情况下效果很好
标签: android android-listview android-custom-view android-cursoradapter