我正在做一个Adroid应用来练习痘痘,但我在这里找到了一些麻烦。我有这个适配器列出一些产品。我可以在活动中看到它们,但TextView为空。
你知道为什么setText()函数不起作用吗? 我认为这将是一个愚蠢的语法错误或类似的东西,但我无法找到它。
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private Cursor cursor;
private boolean full;
public CardAdapter(Cursor c) {
cursor = c;
full = cursor.moveToFirst();
}
@Override
public CardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
try {
if (full) {
String name = cursor.getString(cursor.getColumnIndex("name"));
holder.productName.setText(name);
full = cursor.moveToNext();
if(!full) cursor.close();
}
} catch (Exception e) {
Log.d("ADAPTER", "Error while trying to get rows from database");
}
}
@Override
public int getItemCount() {
int i = cursor.getCount();
if(i > 0) {
full = true;
return i;
}
else {
full = false;
return 0;
}
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView productName;
public ViewHolder(View v) {
super(v);
productName = ((TextView) v.findViewById(R.id.productName));
}
}
}
更新 更改 onBindViewHolder :
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
try {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
holder.productName.setText(name);
notifyItemChanged(position);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d("ADAPTER", "Error while trying to get rows from database");
}
cursor.close();
}
TextView xml:
<TextView
android:id="@+id/productName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
/>
在mainACtivity中,onCreate()上有这个:
pRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pRecyclerView.setHasFixedSize(true);
pLayoutManager = new LinearLayoutManager(this);
productManager = new ProductManager(this);
Cursor c = productManager.getProducts();
pAdapter = new CardAdapter(c);
pRecyclerView.setAdapter(pAdapter);
pRecyclerView.setLayoutManager(pLayoutManager);
解决方案 因为它在我发布的评论中也是如此:textColor设置为白色。天才。
谢谢!
答案 0 :(得分:2)
适配器根据计数(cursor.getCount()
)进行迭代。您可以使用其位置从索引中获取项目。但在你的情况下,你必须迭代自己的。否则,每次调用完整块时都将无效。
尝试: -
if(cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
}while (cursor.moveToNext());
}
cursor.close();
在结束时调用notifyItemPositionChanged()
并为视图传递相同的位置以进行刷新。
答案 1 :(得分:0)
你需要检查full是否为true且name不为null。如果name为null或为null,那么它将在Textview上设置名称变量中没有设置任何其他内容。请调试或添加Log to name in name