我的任务是在用户单击按钮时在第二个活动上绘制形状。所以我尝试了下面的代码,但是没有用。
我已经介绍了很多教程,但是它们都是在另一个View中完成的。我不了解该视图。
MainActivity.java
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
Button draw;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
draw = findViewById(R.id.drawButton);
draw.setOnClickListener(this);
}
@Override
public void onClick(View v) {
shape = dropdown.getSelectedItem().toString();
Bundle b = new Bundle();
b.putString("shape",shape);
Intent i = new Intent(getApplicationContext(),shapes.class);
i.putExtras(b);
startActivity(i);
}
}
Shapes.java
public class shapes extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shapes);
Canvas canvas = new Canvas();
Rect rec = new Rect();
rec.top=100;
rec.left=100;
rec.bottom = rec.top + 100;
rec.right = rec.left+ 100;
Paint p = new Paint();
p.setColor(Color.GREEN);
canvas.drawRect(rec,p);
}
}
答案 0 :(得分:0)
单击按钮时,您正在调用意图,它将创建一个新的活动。您可以在活动主布局中添加一个简单的图像视图,然后可以如下设置画布图形。
ImageView imageView=(ImageView) findViewById(R.id.image);
Bitmap bitmap = Bitmap.createBitmap(100, 100,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
Rect rec = new Rect();
rec.top=0;
rec.left=0;
rec.bottom = rec.top + 100;
rec.right = rec.left+ 100;
canvas.drawRect(rec,paint);
imageView.setImageBitmap(bitmap);