Search code examples
javaandroidgettextandroid-cardviewcardview

How to get text from TextView inside a CardView?


Inside a CardView I have a LinearLayout with three TextViews in it and I want to get the text from these TextViews. My XML-file looks like this:

 <LinearLayout
        android:id="@+id/defense"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        >

        <android.support.v7.widget.CardView
            android:id="@+id/cardCB"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_weight="1"
            app:cardBackgroundColor="@android:color/transparent"
            app:cardElevation="0dp">

          <LinearLayout
              android:id="@+id/innerLayout"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:text="Rannochia"
                  android:textAlignment="center"
                  android:textStyle="bold"/>
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:text="78"
                  android:textAlignment="center"
                  android:textStyle="bold"/>
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:text="CB"
                  android:textAlignment="center"
                  android:textStyle="bold"/>

          </LinearLayout>
        </android.support.v7.widget.CardView>
       </LinearLayout>

Then I want to iterate through all CardViews in the parent LinearLayout and get the TextViews. Something like this:

     for (int i = 0; i < defense.getChildCount(); i++){
        String getName = ((CardView)defense.getChildAt(i)).getText().toString();
        id[i] = getName;
    }

But I'm not able to call the methods getText().toString(); like this. How can I get the text from these TextViews inside the CardView?


Solution

  • So many options in here.
    1. Give id for your TextViews
    2. Use for in LinearLayout with id innerLayout
    3. When your UI is dynamic and you need to get TextViews from defense

    for (int i = 0; i < defense.getChildCount(); i++){
            CardView card = defense.getChildAt(i);
            ViewGroup viewGroup = ((ViewGroup)card.getChildAt(0));
            for(int j=0;j<viewGroup.getChildCount();j++){
                String getName = ((TextView)viewGroup.getChildAt(j)).getText().toString();
                id[i] = getName;
            }
        }