如何以编程方式添加自定义视图

时间:2013-03-18 02:30:02

标签: android android-widget

我创建自定义视图并以编程方式和XML格式添加LinearLayout 但是添加programmaticaly的视图不会调用onDraw(Canvas canv){..} 如果调用XML onDraw中添加的视图为什么? 如何以编程方式添加自定义视图 如果我覆盖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>

0 个答案:

没有答案