开发者

Problem displaying ShapeDrawable in an ImageView

I am writing an app which will create drawable shapes and add them to other drawables. (Think Tetris pieces onto a Tetr开发者_如何学Pythonis 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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜