我的代码出现了一个奇怪的错误。我使用了Recycler View(以前也用过,没有任何问题)。我创建了一个测试ArrayList,想在Recycler View中展示它,但我只得到了第一行,然后应用程序停止运行(不会崩溃),就好像ArrayList已经结束了。
我的主要代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_tab, container, false);
Activity activity = getActivity();
//TODO: For testing ONLY
ArrayList<Order> orders = new ArrayList<>();
for(int i = 0; i < 10; i++) {
orders.add(new Order(i, i, i));
}
// Initialising Orders Recycler View.
OrderAdapter orderAdapter = new OrderAdapter(activity, orders);
RecyclerView recyclerViewOrders = (RecyclerView) view.findViewById(R.id.recylerViewAllDiners);
recyclerViewOrders.setLayoutManager(new LinearLayoutManager(activity));
recyclerViewOrders.setAdapter(orderAdapter);
return view;
}
适配器:
package com.slavafleer.tipcalculator;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Order Adapter for Order Recycler View
*/
public class OrderAdapter extends RecyclerView.Adapter<OrderHolder> {
private Context context;
private ArrayList<Order> orders;
public OrderAdapter(Context context, ArrayList<Order> orders) {
this.context = context;
this.orders = orders;
}
@Override
public OrderHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.item_order, parent, false);
return new OrderHolder(view);
}
// TODO: why it has been done just once ?
@Override
public void onBindViewHolder(OrderHolder holder, int position) {
Order order = orders.get(position);
holder.bindOrder(order);
}
@Override
public int getItemCount() {
return orders.size();
}
}
持有人:
package com.slavafleer.tipcalculator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Order Holder for Order Recycler View
*/
public class OrderHolder extends RecyclerView.ViewHolder {
private TextView textViewOrderId;
private TextView textViewDinerId;
private TextView textViewPrice;
public OrderHolder(View itemView) {
super(itemView);
textViewOrderId = (TextView) itemView.findViewById(R.id.textViewOrderId);
textViewDinerId = (TextView) itemView.findViewById(R.id.textViewDinerId);
textViewPrice = (TextView) itemView.findViewById(R.id.textViewPrice);
}
// Bind Data Object to the Views.
public void bindOrder(Order order) {
textViewOrderId.setText(order.getOrderId() + "");
textViewDinerId.setText(order.getDinerId() + "");
textViewPrice.setText(order.getPrice() + "");
}
}