我的RecyclerView
单行有3列。 2是从SQLite
数据库查询中填充的,另一个是由TextView
填充的。我在如何填充TextView
方面遇到麻烦。目的是通过从一组switch语句中选择的Strings选项来设置TextView
。但是,findViewById
无法解析。是否可以在TextView
内使用onBindViewHolder
?
RecyclerViewAdapter.java
public class UpcomingRecyclerViewAdapter extends RecyclerView.Adapter<UpcomingRecyclerViewAdapter.ViewHolder> {
private Cursor mCursor;
public UpcomingRecyclerViewAdapter(Cursor cursor) {
this.mCursor = cursor;
}
@Override
public UpcomingRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.history_list_items, parent, false);
return new UpcomingRecyclerViewAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(UpcomingRecyclerViewAdapter.ViewHolder holder, int position) {
if ((mCursor != null) && (mCursor.getCount() != 0)) {
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("Couldn't move cursor to position " + position);
}
String name = mCursor.getString(mCursor.getColumnIndex(VehiclesContract.Columns.VEHICLE_NAME));
String miles = mCursor.getString(mCursor.getColumnIndex(VehiclesContract.Columns.VEHICLE_CURRENT));
String maintenance = (TextView) view.findViewById(R.id.up_list_maintenance);
holder.name.setText(name);
holder.miles.setText(miles);
holder.maintenance.setText(maintenance);
}
}
@Override
public int getItemCount() {
return mCursor != null ? mCursor.getCount() : 0;
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView miles;
TextView maintenance;
public ViewHolder(View itemView) {
super(itemView);
this.name = itemView.findViewById(R.id.upcoming_name);
this.miles = itemView.findViewById(R.id.upcoming_miles);
this.maintenance = itemView.findViewById(R.id.upcoming_maintenance);
}
}
答案 0 :(得分:1)
好吧,在这一行
String maintenance = (TextView) view.findViewById(R.id.up_list_maintenance);
您正在尝试分配一个视图到字符串,这是完全错误的。
您可以assign the value of a textfield which is a string to a string variable
,
或assign a textfield to a variable of textfield type.
首先解决此问题,然后查看它是否可以解决您的问题。
答案 1 :(得分:0)
String maintenance = (TextView) view.findViewById(R.id.up_list_maintenance);
findViewById返回一个View。您正在尝试将其转换为字符串。试试这个:
String maintenance = ((TextView) view.findViewById(R.id.up_list_maintenance)).getText().toString();