Sharon182
Sharon182

Reputation: 110

How to change drawable shape size programmatically ?

How can i change the width and height programmatically so the shape will fit the android device it's running on ? the 90dp height fits to my device , but i want it to fit in other devices.

here is my shape.xml code :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cellfilled" >

<size android:width="0dp"
    android:height="90dp" />

<solid android:color="#00000000" />

<stroke
    android:width="1dp"
    android:color="#ff000000"/>

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" />
</shape>

Upvotes: 5

Views: 12878

Answers (2)

kiran boghra
kiran boghra

Reputation: 3822

Use as below,

create circle.xml in drawable

<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >


<solid android:color="#00000000" />

<stroke
android:width="1dp"
android:color="#ff000000"/>

 </shape>

and add view in linearlayout as below with width and height value,

View view = new View(this);
view.setBackgroundResource(R.drawable.circle);
LayoutParams params = new LayoutParams(15, 15);
view.setLayoutParams(params);
linearLayout.addView(view);

Upvotes: 4

xXJJJasonMokXx
xXJJJasonMokXx

Reputation: 367

Sorry, I'm on my phone.

You could try

setBounds()

first, if it doesn't work then you can use the following code:

// Read your drawable from somewhere 
Drawable dr = getResources().getDrawable(R.drawable.somedrawable); 
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap(); 
// Scale it to 50 x 50 
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true)); 
// Set your new, scaled drawable "d"

EDIT:

You can get the size of the display in px in the following code:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);

int width = size.x;
int height = size.y;

and then you can get the relative size to a certain display and use the above answer to change the size of the drawable programmatically. Hope it helps :D

Upvotes: 1

Related Questions