日志和编码部分未显示任何错误。运行时,它仅显示带有虚拟设备的灰色屏幕。因此,我不知道该片段部分发生了什么。基本上,我的活动和Java片段是分开的,因此以下部分是片段编码部分。希望大家能帮助我解决这个问题。谢谢。
public class ProductListFragment extends Fragment {
private RecyclerView mProductRecyclerView;
private ProductAdapter mAdapter;
private class ProductHolder extends RecyclerView.ViewHolder {
private Product mProduct;
private TextView mTitleTextView;
private TextView mPrice;
public ProductHolder(LayoutInflater inflater, ViewGroup parent){
super(inflater.inflate(R.layout.list_item_product,parent, false));
// itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.product_title);
mPrice = (TextView) itemView.findViewById(R.id.price);
}
public void bind(Product product){
mProduct = product;
mTitleTextView.setText(mProduct.getProductName());
mPrice.setText(mProduct.getPrice());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_product_list,container,false);
mProductRecyclerView = (RecyclerView) view.findViewById(R.id.product_recycler_view);
mProductRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI(){
ProductLab productLab = ProductLab.get(getActivity());
List<Product> products = productLab.getProducts();
if (mAdapter ==null){
mAdapter = new ProductAdapter(products);
mProductRecyclerView.setAdapter(mAdapter);
}else{
mAdapter.setProducts(products);
mAdapter.notifyDataSetChanged();
}
}
//Adapter
private class ProductAdapter extends RecyclerView.Adapter<ProductHolder>{
private List<Product> mProducts;
public ProductAdapter(List<Product> products){
mProducts= products;
}
@Override
public ProductHolder onCreateViewHolder(ViewGroup parent,int viewType){
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new ProductHolder(layoutInflater, parent);
}
@Override
public void onBindViewHolder(ProductHolder holder, int position){
Product product = mProducts.get(position);
holder.bind(product);
}
@Override
public int getItemCount(){
return mProducts.size();
}
public void setProducts(List<Product> products){
mProducts= products;
}
}
}
答案 0 :(得分:0)
一个问题是调用updateUI()
函数。您在错误的地方叫它
onCreateView
访问视图元素的好习惯onViewCreated
内调用UI更新功能getActivity()
无处不在,我建议声明一个父活动的类成员,然后在onAttach(context: Context)
函数中对其进行初始化,然后在需要时传递变量