我正在尝试在RecyclerView中显示一个包含图像和文本的列表。该类扩展了片段类,因为它是Tab的一部分。这是我的代码。
这是我的片段类。
myModalObj
这是带有getter和setter方法的模型类。
public class Recharges extends Fragment {
public RecyclerView recyclerView;
private List<GetRecharge> rechargeList = new ArrayList<>();
public RecyclerView.LayoutManager layoutManager;
public Adapter adapter;
ImageView image1, image2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
View rootView = inflater.inflate(R.layout.rechargelist, container, false);
image1 = new ImageView(getContext());
image1.setImageResource(R.drawable.account);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
adapter = (Adapter) new Adapterrecharge(rechargeList);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter((RecyclerView.Adapter) adapter);
prepareRechargeData();
return rootView;
}
private void prepareRechargeData() {
GetRecharge recharge = new GetRecharge("Mad Max: Fury Road", image1 );
rechargeList.add(recharge);
//recharge = new GetRecharge("Inside Out", "Animation, Kids & Family", "2015");
//rechargeList.add(recharge);
adapter.notifyDataSetChanged();
}
这是适配器类
public class GetRecharge {
private String title;
ImageView image;
public GetRecharge() {
}
public GetRecharge(String title, ImageView image) {
this.title = title;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public ImageView getImage() {
return image;
}
public void setImage(ImageView image) {
this.image = image;
}
}
答案 0 :(得分:1)
下面:
image1 = new ImageView(getContext());
仅创建ImageView
对象而不为View设置LayoutParams
。这样做:
image1 = new ImageView(getContext());
image1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
image1.setImageResource(R.drawable.account);
另一种或简单的方法就是将R.drawable.account
int id传递给GetRecharge
并调用:
holder.image.setImageResource(recharge.getImage());