I am looking into designing my app to work with Android L and designing it to use the new Material Design.
I'm looking into the example of the RecyclerView at https://developer.android.com/preview/material/ui-widgets.html but the example doesn't compile.
Below is my activity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] myDataset = new String[2];
myDataset[0] = "Hello";
myDataset[1] = "World";
setContentView(R.layout.activity_recylcer);
mRecyclerView = (RecyclerView)findViewById(R.id.recylcerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
Below is my MyAdapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
// Provide a reference to the type of views that you are using
// (custom viewholder)
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
}
The problem that I have, when I create the instance of the ViewHolder the example says to pass in the variable v which is a View but Android Studio is saying that it expects a TextView.
I'm assuming I've done some wrong as I would like to think that the examples that Google's Android Development Site would have correct code but I can't see for the life of me what I could have got wrong.
As far as I see, it expects TextView because you request TextView in the constructor of your ViewHolder static class. Change that to View. It might help.
If you don't want to change the constructor like Boldizsar said, then why don't you try to cast your inflated view as a TextView and create a viewholder with that textview.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With