简体   繁体   中英

How to use a drawable shape in Android through Java?

If I have a drawable shape:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
 android:shape="rectangle"> 
 <stroke android:width="2dp" android:color="#FFFFFFFF" />
 <gradient android:startColor="#DD000000" android:endColor="#DD2ECCFA" 
        android:angle="225"/> 

<corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" 
 android:topLeftRadius="7dp" android:topRightRadius="7dp"/> 
</shape> 

How would I go about using this as the background for a textview? I tried something like below, but it didn't work.

TextView jObjTv = new TextView(getActivity());
jObjTv.setBackgroundDrawable(findViewById(R.drawable.sample_box));

The code you posted doesn't work because a drawable isn't a view and isn't a part of the layout.

You need to call textView.setBackgroundResource(R.drawable.sample_box) if you want to use the resource. If you want to use the Drawable, you need to create the Drawable using context.getResources().getDrawable(R.drawable.sample_box) .

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