如何在setContentView(R.layout.main)之后调用onDraw?

3

我需要在运行时绘制一些东西。我在MyView类的onDraw方法中进行绘制。 因为我已经在onCreate中使用了setContentView(R.layout.main),所以我不能再次使用它。
如何在setContentView(R.layout.main)后调用onDraw方法?

public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // I have something to draw in XML also.
        MyView myView = new MyView(this);
        // setContentView(myView); I cannot use setContentView two times.
}
protected class MyView extends View {
    public MyView(Context context) {
        super(context);
    }
    public void onDraw(Canvas canvas) {
           // there are some drawing codes and these cannot be done in XML.
    }
}
3个回答

2
我看到两种方法:
1:您可以将您的myView(实例)添加到在R.layout.main中定义的ViewGroup中。
2:您可以直接在XML R.layout.main中使用MyView。而不是“LinearLayout”等,您可以使用完全限定的类名。
请参见http://developer.android.com/guide/topics/ui/custom-components.html(底部)。

我还没有尝试过,但我认为它会起作用。这就像使用自定义小部件一样。 - user1301568

1

你不应该自己调用 onDraw() 方法。相反,如果要强制重绘,请调用 invalidate() 方法。

如果视图可见,则 onDraw(android.graphics.Canvas) 方法将在将来的某个时间点被调用。


我在onCreate中调用了myView.invalidate();,放在了setContentView(R.layout.main);之后。但是它没有起作用。我应该在哪里调用invalidate? - user1301568
我猜你没有将你的视图添加到活动中。除非将视图添加到视图层次结构中,否则活动不能显示视图。根据您的需求,您可能需要将它添加到层次结构中的特定布局中。 - Dheeraj Vepakomma

0
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);

    MakeView makeView = new MakeView(this);

    relativeLayout.addView(makeView);
    relativeLayout.invalidate();
}

我注意到在addView之后会调用onDraw方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接