Search code examples
androidimageviewtablerow

Android imageview not displaying in TableRow


I am trying to display a simple ImageView in a TableRow but for some reason it won't display. If I add another control to another row the imageView does display, so it seems like it is just not forcing the size correctly. My xml is as follows:

<TableLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="fill_parent" 
  android:layout_width="fill_parent"
 android:background="#4B088A"
  android:id="@+id/ImageTable">

 <TableRow android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
 android:padding="5dp"
 android:id="@+id/ImageTableRow"/> 

  </TableLayout>

The code that I am using to add the ImageView is:

TableLayout tableLayout = (TableLayout) findViewById(R.id.ImageTable);  

TableRow tr = new TableRow(this);

TableRow.LayoutParams lp = new 
        TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT ,TableRow.LayoutParams.WRAP_CONTENT);

tr.setLayoutParams(lp);

 m_imageView = new MyImageView(getApplicationContext());

 m_imageView.setBackgroundColor(Color.GRAY);

 m_imageView.setImageBitmap(charty);

 tr.addView(m_imageView);

 tableLayout.addView(tr);

Solution

  • Try this code:

    Write your activity_main.xml as

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TableRow
                android:id="@+id/tableRow1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                <ImageView
                    android:id="@+id/image"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_action_search" />
            </TableRow>
        </TableLayout>
    </LinearLayout>
    

    ic_action_search is your image in the "Drawable" folder, and write MainActivity.java as

    public class MainActivity extends Activity {
        
        ImageView image;
        
        @Override
        public void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }