Ci3
Ci3

Reputation: 4842

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));

Upvotes: 0

Views: 645

Answers (1)

toadzky
toadzky

Reputation: 3846

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).

Upvotes: 3

Related Questions