Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

android - recyclerView.setAdapter does not accept ArrayAdapter

I am trying to populate RecyclerView with simple String data but recyclerView.setAdapter(adapter); gives error. What's the problem?

I am new to recyclerview.

RecyclerView recyclerView;
String []data = {"ankush", "kapoor"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to create a custom Adapter class for a RecyclerView. Here is the example of RecyclerView custom adapter class :

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{

private LayoutInflater inflater;
private Context context;
<your string array list>

public CustomAdapter(Context context,<your string arraylist>) {
    inflater = LayoutInflater.from(context);
    this.context = context;
    this.<your string arraylist>=<your string arraylist>;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.custom_layout, parent, false);
    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
         holder.serial_number.setText(<your string array[position]>);
}

@Override
public int getItemCount() {
    return <size of your string array list>;
}

class MyViewHolder extends RecyclerView.ViewHolder
{
    TextView serial_number;

    public MyViewHolder(View itemView) {
        super(itemView);
        serial_number = (TextView)itemView.findViewById(R.id.serialNo_CL);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...