gpt4 book ai didi

android - 为什么这个 `onDraw` 没有被触发?

转载 作者:行者123 更新时间:2023-11-30 04:02:43 24 4
gpt4 key购买 nike

我有一个扩展 View 的自定义 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>

在我的 Activity 中,当单击按钮 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 方法似乎没有触发,如何解决?

最佳答案

您必须为 drawables 设置边界。

像这样:

drawable.setBounds(10,10,100,100); 
this.drawables.add(drawable);

关于android - 为什么这个 `onDraw` 没有被触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com