View in RecyclerView does not match parent width

后端 未结 2 1476
粉色の甜心
粉色の甜心 2021-01-13 07:29

I have a horizontal recyclerview:



        
相关标签:
2条回答
  • 2021-01-13 08:04

    RecyclerView is very crappy when it comes to properly positioning it and/or its child views. Try

    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        final View v = inflater.inflate(R.layout.item, parent, false);
    
        // match_parent won't work for RecyclerView (sigh)
        final ViewGroup.LayoutParams lp = v.getLayoutParams();
        lp.width = parent.getWidth();
        lp.height = parent.getHeight();
        v.setLayoutParams(lp);
    
        return new ViewHolder(v);
    }
    

    which basically replaces match_parent for both height & width within the child view. For your particular case you would only set the width then.

    0 讨论(0)
  • 2021-01-13 08:09

    i think the problem is from

    vg.getContext()

    Let change to applicationContext or pass context to CustomAdapter

    0 讨论(0)
提交回复
热议问题