在已创建的ImageView上设置Drawable可以工作,但不能在新的ImageView中工作

时间:2018-03-21 09:29:36

标签: android imageview android-drawable

我试图将ImageViews动态添加到已创建的RelativeLayout中。但是,图像没有显示。

这是我layout.xml的相关部分:

<RelativeLayout
     android:id="@+id/servicesRelativeLayout"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">

     <ImageView
         android:id="@+id/servicesImgView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/campsite_icon" />
</RelativeLayout>

这是我的代码:

RelativeLayout servicesRelativeLayout = (RelativeLayout) findViewById(R.id.servicesRelativeLayout);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
    );
layoutParams.setMarginStart(44);
layoutParams.setMarginEnd(10);

for (String availableService : getServices()) {
    @DrawableRes int resID = getResources().getIdentifier(
        "service_" + availableService.toLowerCase(),
        "drawable",
        getPackageName()
    );

    if (resID != 0) {
        ImageView availableServiceImgView = new ImageView(this);
        availableServiceImgView.setImageResource(resID);
        availableServiceImgView.setLayoutParams(layoutParams);
        servicesRelativeLayout.addView(availableServiceImgView);
    }
}

注解:

  • 正在创建ImageView,并将其添加到servicesRelativeLayout(使用调试器进行测试)。
  • resID存在,我测试过它使用该资源ID填充现有的ImageView(servicesImgView)。
  • servicesImgView显示
  • 如果我在for循环之前执行servicesRelativeLayout.removeAllViews();,则会删除servicesImgView并按预期添加新视图,但不显示任何内容

有关为什么没有显示这些Drawables的任何想法?我尝试使用Drawable.createFromStream加载资源而不是Drawables,但是并没有真正起作用。我想我错过了一些与动态ImageView相关的东西。

2 个答案:

答案 0 :(得分:0)

请检查此资源是否存在。

"service_" + availableService.toLowerCase()

答案 1 :(得分:0)

&#39;有罪&#39;代码是与LayoutParams相关的代码。删除该行使得要绘制的drawable:

availableServiceImgView.setLayoutParams(layoutParams);

不知何故,我没有以正确的方式构建LayoutParams。

我决定更改LinearLayout的RelativeLayout,并将边距调整为我想要的:

LinearLayout servicesLinearLayout = (LinearLayout) findViewById(R.id.servicesLinearLayout);
servicesLinearLayout.removeAllViews();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT
);
layoutParams.setMarginStart(10);
layoutParams.setMarginEnd(10);

我认为我不完全理解RelativeLayout类,因为图像根本没有显示,甚至没有以错误的方式显示。

相关问题