Problem displaying ShapeDrawable in ImageView

I am writing an application that will create populated shapes and add them to other drawings. (Think of the tetris appearing on the Tetris board.) As a test, I want a specific shape to appear when my activity loads, but I can't get Drawable to appear in the ImageView that I created. Can someone explain why the following code is not working?

Operation 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 was able to make static resources from the "drawable" folder in this ImageView, and not in the Drawables that I created in the code.

+4
source share
2 answers

You can also use a simple view and simply set its background image to a form using setBackgroundDrawable .

ImageView probably cannot display your shape as it does not have a default size. You can set your form to a default parameter using sD.setIntrinsicWidth and sD.setIntrinsicHeight .

+15
source

alternatively, you can create your own custom view by expanding the presentation class. I believe that Drawable objects can only be processed from a custom view. just create and render the drawable method in onDraw()

+1
source

All Articles