如何在 Android 运行时实例化 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 一样对待它,但为什么我不能让它显示?我错过了什么吗?
谢谢!
I have a class that is extending ImageView. I want to instantiate this class run time in my Android activity but can't get it to show. If I on the other hand call it from xml, it shows.
This works:
PanelChart pc = (PanelChart) findViewById(R.id.pc);
With 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"/>
This doesn't work:
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);
My feeling is I should be able to treat it just like a normal imageView, but why can't I get it to show? Am I missing something?
THanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查代码顶部的导入,您应该有
import android.view.ViewGroup.LayoutParams
用于在相对布局中设置布局参数,还
import android.widget.TableRow.LayoutParams< /code>
用于设置表格行布局参数。你两者都有吗?
如果您这样做,请尝试在 xml 中设置相对布局,然后只需添加表格布局和布局即可。行到那。
Check your imports at the top of your code you should have
import android.view.ViewGroup.LayoutParams
For setting the layout parameters in your relative layout and also
import android.widget.TableRow.LayoutParams
for setting the table row layout parameters. Do you have both?
If you do then try setting up the relative layout in your xml then just adding the table layout & rows to that.