简体   繁体   中英

How can I set an XML drawable as a background image programatically?

I designed an image in xml, and put it under my drawable resources

ic_receive.xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:pathData="M0,10.5016l19.5008,0l0,10.4968l-19.5008,0z"
      android:strokeWidth="1"
      android:fillColor="#C6ECCB"
      android:fillType="nonZero"
      android:strokeColor="#00000000"/>
  <path
      android:pathData="M4.5,3.0016l19.5,0l0,10.4968l-19.5,0z"
      android:strokeWidth="1"
      android:fillColor="#41BF53"
      android:fillType="nonZero"
      android:strokeColor="#00000000"/>
  <path
      android:pathData="M18,7.5l-3,0l0,-3l-1.5,0l0,3l-2.9992,0l0,1.5l2.9992,0l0,3l1.5,0l0,-3l3,0z"
      android:strokeWidth="1"
      android:fillColor="#C6ECCB"
      android:fillType="nonZero"
      android:strokeColor="#00000000"/>
</vector>

I tried setting the image programatically in a Recycler View in my Fragment

TransactionsFragment.java

TransactionsModel options = new TransactionsModel("Approved", "$ 3,000", R.drawable.ic_receive, R.drawable.ic_action_home);
        transactionsList.add(options);

When I run the app, the ImageView turns out blank, but when use a .png drawable, it shows fine, like the R.drawable.ic_action_home used for another ImageView.

Note

I also noticed that, the xml image shows fine in the tiny preview by the right of the code that sets the drawable

Other tutorials like this one( Set background to a drawable programatically ), seemingly point to the same way of setting the drawable resource, but still not working for me.

Does anyone have any idea as to why this may be? could I have missed or omitted something?

BTW, I'm using the new AndroidX if that matters and can also provide more code if needed.

Cheers!

EDIT

Code used to display the image in recycler view

 public void onBindViewHolder(MyViewHolder holder, int position) {

        TransactionsModel movie = transactionsList.get(position);
        Glide.with(mCtx)
                .load(movie.getTxIcon())
                .into(holder.txIcon);

    }

You can use this snippet to set drawable as a background.

imageView.setBackgroundResource(R.drawable.bgg);
imageView.setBackgroundDrawable(R.drawable.bgg);

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