我创建自定义视图并以编程方式添加到 LinearLayout 和以编程方式添加的 XML BUT 视图中,如果在 XML onDraw 中添加的视图被调用,则不会调用 onDraw(Canvas canv) {..} 为什么?如何以编程方式添加自定义视图?如果我覆盖 onMeasure 方法,onDraw 不会调用
看法:
package com.android.timetable;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
public class TestView extends View {
public TestView(Context context) {
super(context);
}
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
活动:
package com.android.timetable;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class testActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
LinearLayout main = (LinearLayout)findViewById(R.id.main);
TestView test = new TestView(this, null);
main.addView(test, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.android.timetable.TestView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>