How to programatically change a TextView to an ImageView and back

android, android-imageview, textview

Solution

Just add an ImageView below / next to your TextView and set the android:visibility="gone" on the one you don't want to show.

Also set an android:id="@+id/some_identifier" so that you can find the view in code and set the TextView to View.GONE and the ImageView to View.VISIBLE when you want to switch.

<LinearLayout
    android:layout_width="320dp"
    android:layout_height="50dp" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.35"
        android:text="      "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ImageView
        android:id="@+id/image_view_1"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Problem

I have an XML layout that defines a `TextView` box 50px x 320px who ID is `TextView2`. I want to use the same `TextView` area to show an image sometimes. I want to programatically be able to switch that area to be either `TextView` or `ImageView`. ``` <LinearLayout android:layout_width="320dp" android:layout_height="50dp" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.35" android:text=" " android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> ```

Original source