Search code examples
androidandroid-recyclerviewandroid-viewholder

How to instead "View inflate(int resource,ViewGroup root, boolean attachToRoot)" method when the View just a Simple View used "new TextView"?


When I use the Adapter of a RecyclerView to create ViewHolder, the view is just a TextView, so I don't want use LayoutInflate.inflate() with a layout.xml file. Therefore I create a TextView instance via constructor, but the TextView shows nothing. Now I want know if there is a way to solve this?

  1. I write parent.addView(textview) before return, but it crashed.
  2. When I write a layout.xml and use LayoutInflate.from().inflate(), it works well.
    @Override
    public GeekSearchWordItemAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        TextView textView = new TextView(mActivity);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, R.dimen.text_size_medium);
        textView.setTextColor(ContextCompat.getColor(mActivity, R.color.text_c6));
        return new ViewHolder(textView);
    }
    ...
    @Override
    public void onBindViewHolder(@NonNull GeekSearchWordItemAdapter.ViewHolder holder, int position) {
        LevelBean bean = LList.getElement(mDatas, position);
        if (bean != null) {
            holder.mTxtName.setText(bean.name);
        }
    }
    ...
    static class ViewHolder extends RecyclerView.ViewHolder {
        private TextView mTxtName;

        public ViewHolder(View itemView) {
            super(itemView);
            mTxtName = (TextView) itemView;
        }
    }

Solution

  • In onCreateViewHolder() try to add layout params to the TextView you creates there.

    RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(
                     RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT);
    textView.setLayoutParams(params);