在OrderHistoryActivity Activity中,在XML中使用RecyclerView并在OrderHistoryActivity.java中创建对象。
创建item.xml文件
注:它要求你正在使用activity_order_history (OrderHistoryActivity xml文件)的viewHolder错误。<?xml version="1.0" encoding="utf-8"?>
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
android:id="@+id/orderid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
现在将OrderHistoryRecyclerAdapter.java修改为:package com.tesmachino.saycure;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.tesmachino.saycure.entities.OrderHistory.OrderHistoryResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
public class OrderHistoryRecyclerAdapter extends RecyclerView.Adapter {
private List data;
public OrderHistoryRecyclerAdapter(List data){
this.data = data;
}
@NonNull
@Override
public OrderHistoryRecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item.xml, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull OrderHistoryRecyclerAdapter.ViewHolder holder, int position) {
OrderHistoryGet obj = data.get(position);
holder.order_id.setText(obj.getId()+"");
}
@Override
public int getItemCount() {
return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView order_id;
public ViewHolder(@NonNull View itemView) {
super(itemView);
order_id = (TextView) itemView.findViewById(R.id.orderid);
}
}
}
现在在onResponse方法中这样做。....
@Override
public void onResponse(Call call, Response response) {
Toast.makeText(OrderHistoryActivity.this,"" + response.body().getData(), Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
@Override
public void run() {
OrderHistoryRecyclerAdapter adapter = new OrderHistoryRecyclerAdapter(response.body().getData());
//This recyclerView object should create before, like findViewById(R.id.recyclerViewIdinXML)
RecyclerView.LayoutManager manager=new LinearLayoutManager(getContext());
((LinearLayoutManager) manager).setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(manager);
recyclerView.setAdapter(adapter);
}
});
}
...
就是这样。