按按钮更改同一Java Activity的内容

时间:2015-07-04 17:08:06

标签: android

当我运行以下代码时,首先我看到一个红色矩形。

但我想首先看到一个绿色矩形,然后当我按下按钮时,接下来会看到同一活动中的一个红色矩形。

解决方案是什么?

MainActivity.java

public class MainActivity extends Activity {
Button button;
    Draw draw;
    Draw2 draw2;
    RelativeLayout linearLayout;
    public void onCreate(Bundle s) {
        super.onCreate(s);
        setContentView(R.layout.activity_main);

        linearLayout = (RelativeLayout) findViewById(R.id.t);
button = (Button) findViewById(R.id.button);

 draw = new Draw(this);

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(200, 200);
        draw.setLayoutParams(layoutParams);

        linearLayout.addView(draw);

        button.setOnClickListener(new View.OnClickListener() {


            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Draw2.class);
                startActivity(intent);
            }
        });
        draw2 = new Draw2(this);
        draw2.setLayoutParams(layoutParams);
        linearLayout.addView(draw2);
    }

}

Draw.java

public class Draw extends View {
    Paint paint;

    public Draw(Context context) {
        super(context);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

@Override
    protected  void onDraw(Canvas canvas) {
    paint.setColor(Color.GREEN);
    canvas.drawRect(50,30,100,120,paint);
    super.onDraw(canvas);
    }}

Draw2.java

public class Draw2 extends View {
    Paint paint;
    Draw2(Context context){
        super(context);
      paint = new Paint();
    }
@Override
    protected void onDraw(Canvas canvas){
    paint.setColor(Color.RED);
    canvas.drawRect(50,30,100,120,paint);
super.onDraw(canvas);
}
}

1 个答案:

答案 0 :(得分:0)

Draw2只是一个视图而非活动,所以像这样改变MainActivity

public class MainActivity extends Activity {
     Button button;
     Draw draw;
     Draw2 draw2;
     RelativeLayout linearLayout;
     ViewGroup.LayoutParams layoutParams;

public void onCreate(Bundle s) {
    super.onCreate(s);
    setContentView(R.layout.activity_main);

    linearLayout = (RelativeLayout) findViewById(R.id.container);
    button = (Button) findViewById(R.id.button1);

    draw = new Draw(this);

    layoutParams = new ViewGroup.LayoutParams(200, 200);
    draw.setLayoutParams(layoutParams);

    linearLayout.addView(draw);

    button.setOnClickListener(new View.OnClickListener() {


        public void onClick(View v) {
            draw2 = new Draw2(getApplicationContext());
            draw2.setLayoutParams(layoutParams);
            linearLayout.addView(draw2);
        }
    });

}

}