如何在Android中运行时实例化ImageView?

时间:2011-06-26 19:02:49

标签: android runtime imageview

我有一个扩展ImageView的类。我想在我的Android活动中实例化此类运行时,但无法显示它。另一方面,如果我从xml调用它,它会显示。

这有效:

PanelChart pc = (PanelChart) findViewById(R.id.pc);

使用xml:

    <com.example.android.PanelChart android:id="@+id/pc" android:layout_width="30dip" android:layout_height="30dip" 
android:background="@color/marker_color" android:layout_alignParentRight="true" android:layout_marginRight="15dip"
android:layout_marginTop="42dip"/> 

这不起作用:

 PanelChart pc = new PanelChart(this);
            pc.setParameter(new String(stringParameter));
            pc.setLayoutParams(params);
            pc.setVisibility(View.VISIBLE);

                RelativeLayout rel = new RelativeLayout(this);
            rel.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));

            tr = new TableRow(this);

            tr.setLayoutParams(new TableRow.LayoutParams(
                    TableRow.LayoutParams.WRAP_CONTENT,
                    TableRow.LayoutParams.WRAP_CONTENT));
            rel.addView(pc);
            tr.addView(rel);
            tablelayout.addView(tr);

我的感觉是我应该像普通的imageView一样对待它,但为什么我不能让它显示出来?我错过了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

检查您应该拥有的代码顶部的导入

  1. import android.view.ViewGroup.LayoutParams
  2. 用于设置相对布局中的布局参数以及

    1. import android.widget.TableRow.LayoutParams
    2. 用于设置表格行布局参数。你有两个吗?

      如果你这样做,那么尝试在xml中设置相对布局,然后只需添加表格布局&amp;行到那。

相关问题