Добавление textview динамически в CardView - PullRequest
0 голосов
/ 21 июня 2019

Итак, у меня есть представление карты, созданное следующим образом:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/timeline"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />
         <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/website"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />
    </LinearLayout>

И в моем классе адаптера у меня есть следующий код для заполнения вида карты.

public class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_title, tv_timeline, tv_website;

        public MyViewHolder(View view) {
            super(view);
            tv_title = (TextView) view.findViewById(R.id.title);
            tv_timeline = (TextView) view.findViewById(R.id.timeline);
            tv_website = (TextView) view.findViewById(R.id.website);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_row_data, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {

            holder.tv_title.setText(mTitleList.get(position));                
      holder.tv_timeline.setText(mtimelineList.get(position));
            holder.tv_website.setText(mSiteSrc.get(position));

    }

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

Это правильно показывает вывод, который я ожидаю.Проблема в том, что CardView показывает мне только 3 предмета в моих 3 TextView, а затем продолжает создавать новые карты, содержащие до 3 предметов, чтобы показать мне все остальное.То, что я хотел бы сделать, это использовать текстовую шкалу «timeline» в качестве заголовка, а затем динамически добавлять контент для текстового представления «title» only .Так, например, у меня может быть карточка с 1 «временной шкалой» TextView, 0, 2, 5 и т. Д. «Title» TextView, 1 «веб-сайт» TextView

Может ли это бытьбыть сделано с CardView?Если да, я буду признателен за полезные советы, которые помогут мне начать работу.

Ответы [ 2 ]

0 голосов
/ 21 июня 2019

Конвертируйте ваш xml:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/timeline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp" />
     <LienarLayout
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="vertical"/>
    <TextView
        android:id="@+id/website"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp" />
</LinearLayout>

Теперь в вашем onBindViewHolder добавьте динамические TextViews к заголовку:

   public class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_timeline, tv_website;
        private LinearLayout title; 

        public MyViewHolder(View view) {
            super(view);
            title = (LinearLayout) view.findViewById(R.id.title);
            tv_timeline = (TextView) view.findViewById(R.id.timeline);
            tv_website = (TextView) view.findViewById(R.id.website);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_row_data, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {

      holder.tv_timeline.setText(mtimelineList.get(position));
      holder.tv_website.setText(mSiteSrc.get(position));
      for(int i = 0; i < 5; i++) { // 5 is the count how many times you want to add textview
          LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
          TextView tv=new TextView(holder.title.getContext());
          tv.setLayoutParams(lparams);
          tv.setText("test = "+i);
          holder.title.addView(tv);
}

    }

    @Override
    public int getItemCount() {
        return mTitleList.size();
    }
0 голосов
/ 21 июня 2019

Если я правильно понял вопрос, который вы хотите динамически поместить только часть данных.Таким образом, в держателе bindView связывать только динамическую часть, которая является статической, вы можете жестко запрограммировать в XML-файле со строковым значением.

...