1

我有一个正在扩展的自定义视图View

public class MyView extends View {

    public List<Drawable> drawables = new ArrayList<Drawable>();

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void addDrawable(Drawable drawable) {
        this.drawables.add(drawable);
        Log.i("myview", "new drawable added: " + drawables.size());
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i("myview", "on draw, my drawables: " + drawables.size());
        for (Drawable d : drawables) {
            d.draw(canvas);
            Log.i("myview", "Draw drawable: " + d);
        }
    }
}

我在 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">

    <Button android:id="@+id/btnAdd"
            android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="add"/>

    <com.example.MyView android:id="@+id/imageView"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:background="#6699cc">
    </com.example.MyView>

</LinearLayout>

在我的活动中,当单击按钮时Add,将添加一个可绘制对象MyView

public class MyActivity extends Activity {

    private Button btnAdd;
    private MyView myView;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViews();
        setListeners();
    }

    private void setListeners() {
        this.btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.addDrawable(getResources().getDrawable(R.drawable.m1));
            }
        });
        this.myView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    private void findViews() {
        this.myView = (MyView) findViewById(R.id.imageView);
        this.btnAdd = (Button) findViewById(R.id.btnAdd);
    }

}

但它不起作用。当我单击“添加”按钮时,控制台会打印:

09-02 17:07:27.015: INFO/myview(1748): new drawable added: 1

并且屏幕没有显示图像。该onDraw方法似乎没有触发,如何解决?

4

1 回答 1

1

您必须为drawables.

像这样的东西:

drawable.setBounds(10,10,100,100); 
this.drawables.add(drawable);
于 2012-09-03T03:22:59.777 回答