java - 为什么我的 View 没有改变?

标签 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>

最佳答案

使用 addView 方法将您在 generate() 方法中创建的新 View 添加到 Activity View 。

关于java - 为什么我的 View 没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21362605/

相关文章:

java - PHP 和 Android 上的椭圆曲线密码学

java - Android 将数据从主 UI 线程发送到另一个线程

android - dlopen 在旧版 Android 上失败

android - 如何在 ListView 上设置 onitemclicklistener

java - 使用 sleep 能否保证线程的执行顺序?

java - Android 中的 SQLite 按 AM/PM 时间排序

java - 如何防止 Escape 键关闭 JFace 对话框

java - 正确识别作为 varargs 参数传递的 int[]

android - Facebook token 身份验证在 Android 上失败但在浏览器上失败

安卓工作室 : Inserting files into the Assets folder