Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem displaying ShapeDrawable in an ImageView

Tags:

android

I am writing an app which will create drawable shapes and add them to other drawables. (Think Tetris pieces onto a Tetris board.) As a test, I want to have a particular shape appear when my activity is loaded, but I cannot get a Drawable to appear in the ImageView I created. Could anyone explain why the following code isn't working?

Activity code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView mImg = (ImageView) findViewById(R.id.img);

    ShapeDrawable sD = new ShapeDrawable(new RectShape());
    sD.setBounds(1,1,10,10);
    sD.getPaint().setColor(Color.BLUE);

    mImg.setImageDrawable(sD);
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ImageView
        android:id="@+id/img"
        android:layout_width="320px"
        android:layout_height="206px"
        />
    <TextView
        android:id="@+id/debug"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Note: I have been able to make static resources from the 'drawable' folder appear in this ImageView, just not Drawables I have created in the code.

like image 772
AG. Avatar asked Dec 03 '22 06:12

AG.


2 Answers

You can also use a simple View and just set its background drawable to the shape using setBackgroundDrawable.

The ImageView probably can't display your shape because it has no default size. You can give your shape a default sizer using sD.setIntrinsicWidth and sD.setIntrinsicHeight.

like image 147
Roman Nurik Avatar answered Jan 05 '23 06:01

Roman Nurik


alternatively you can create your own custom view by extending the view class. I suppose Drawable objects can only be handled from within a custom view. just create and render the drawable in the onDraw() method

like image 21
Kshitij Aggarwal Avatar answered Jan 05 '23 08:01

Kshitij Aggarwal