Create or inflate views programmatically in a RecyclerView OnCreateViewHolder

雨燕双飞 提交于 2019-12-05 21:49:47

Finally after getting suggestion, i get the solution of my question,

public class ACShare extends RecyclerView.Adapter<ACShare.VHShare>{

private List<Integer> listDrawalbe;
private ProcessedResult listener;

public ACShare(Fragment context) {
    listener=(ProcessedResult)context;
    TypedArray drawables = context.getActivity().getResources().obtainTypedArray(R.array.s_array_contact_us_share);
    listDrawalbe=new ArrayList<>();
    for (int i = 0; i <  drawables.length(); ++i)
        listDrawalbe.add( drawables.getResourceId(i, -1));
    drawables.recycle();
}

@Override
public VHShare onCreateViewHolder(ViewGroup parent, int viewType) {

    Context context= GeneralFunction.getActivity(parent);
    LinearLayout ll = new LinearLayout(context);
    RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT);
    ll.setLayoutParams(layoutParams);
    ll.setBackgroundColor(GeneralFunction.getColor(context,R.color.color_tranparent));

    return new VHShare(ll);
}

@Override
public void onBindViewHolder(VHShare holder, int position) {
    holder.imageView.setImageResource(listDrawalbe.get(position));
}

@Override
public int getItemCount() {
    return listDrawalbe.size();
}

class VHShare extends RecyclerView.ViewHolder implements View.OnClickListener
{
    public ImageView imageView;

    VHShare(View itemView) {
        super(itemView);

        Context context= GeneralFunction.getActivity(itemView);

        imageView = new ImageView(context);
        LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        int padding= (int) context.getResources().getDimension(R.dimen.elevation_header);
        layoutParams.setMargins(padding,padding,padding,padding);
        imageView.setLayoutParams(layoutParams);

        imageView.setPadding(padding,padding,padding,padding);

        LinearLayout linearLayout=(LinearLayout)itemView;
        linearLayout.addView(imageView);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        listener.processedResult(getPosition(), CallBackConstants.MESSAGE);
    }
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!