为什么我的视图没有改变?

时间:2014-01-26 11:06:48

标签: java android

我有以下代码:

public class DrawView extends View {
    Paint paint = new Paint();

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

    @Override
    public void onDraw(Canvas canvas) {
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(30, 30, 80, 80, paint);
        paint.setStrokeWidth(0);
        paint.setColor(Color.CYAN);
        canvas.drawRect(33, 60, 77, 77, paint );
        paint.setColor(Color.YELLOW);
        canvas.drawRect(33, 33, 77, 60, paint );

    }
}

和主要课程:

public class MainActivity extends Activity {

    DrawView drawView;
    Button btn;
    View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button1);
        view = (View) findViewById(R.id.view1);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                generate();
            }
        });

    }

    public void generate() {
        drawView = new DrawView(this);
        drawView.setBackgroundColor(Color.WHITE);

        view = drawView;
    }
}

问题是:当我点击按钮时,我看不到DrawView,我不知道为什么。

编辑:这是xml代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/generate" />

    <View
        android:id="@+id/view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

1 个答案:

答案 0 :(得分:2)

使用addView方法将您在generate()方法中创建的新视图添加到活动视图。