简体   繁体   中英

ImageView In TableLayout

I want to add a ImageView in TableLayout. I do all things, but it isn't shown anything. How can I fix it?

This is my code:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.buddy_list);

   TableLayout buddy_list_layout = (TableLayout)findViewById(R.id.buddy_list_layout);

    TableRow tableRow = new TableRow(this);
    TableLayout.LayoutParams layoutParams1 = new TableLayout.LayoutParams(
    TableLayout.LayoutParams.FILL_PARENT,
        50);

    ImageView imageView = new ImageView(this);
    imageView.setImageResource(R.drawable.troll_logo);
    TableLayout.LayoutParams layoutParams2 = new TableLayout.LayoutParams(50, 50);
    tableRow.addView(imageView, layoutParams2);
    buddy_list_layout.addView(tableRow, layoutParams1);
} // end -> method -> onCreate

You should switch layoutParams2 from a TableLayout.LayoutParams() to a TableRow.LayoutParams() , since you are using it to add a TableRow. The types need to match the layout, otherwise it won't work.

Try using a pre-defined xml layout for rows, like someone suggests here: https://stackoverflow.com/a/8679835/375929 (you probably don't want it completely dynamic, your rows are most likely similar, you just need to add them dynamically) It will save you the effort of LayoutParams stuff programmatically.

But yeah, your problem is probably using the wrong LayoutParams class, as matt5784 says.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM