我在Android中重绘了与无效问题相关的问题。我有一个简单的活动,它创建一个按钮并显示我的自定义视图(drawGrid
类)。我试图在onClick事件后重新绘制网格加上一行。我的主要问题是,我如何从drawGrid
课程中重新粉饰?任何在正确方向的推动都将在这里受到赞赏。
public class MainActivity extends Activity implements View.OnClickListener {
DrawGrid drawGrid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawGrid = new DrawGrid(this);
drawGrid.setBackgroundColor(Color.BLACK);
setContentView(R.layout.activity_main);
View ballButton2 = findViewById(R.id.right_btn);
ballButton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.right_btn:
drawGrid.move();
}
}
}
public class DrawGrid extends View {
int x = 25;
int y = 25;
int index = 0;
public ArrayList<ArrayList<Integer>> playerOneRed = new ArrayList<>(100);
Paint paint = new Paint();
public DrawGrid(Context context) {
super(context);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(2);
this.setBackgroundColor(Color.BLACK);
}
public DrawGrid(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public DrawGrid(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
paint.setColor(Color.BLUE);
paint.setStrokeWidth(2);
this.setBackgroundColor(Color.BLACK);
}
@Override
public void onDraw(Canvas canvas) {
Log.d("MyApp", "x is " + x);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(3);
for (int i = 0; i < 3000; i = i + 40) {
canvas.drawLine(i, 0, i, 3000, paint);
}
for (int i = 0; i < 3000; i = i + 40) {
canvas.drawLine(0, i, 3000, i, paint);
}
paint.setColor(Color.RED);
paint.setStrokeWidth(8);
// canvas.drawLine(0, 1000, 3000, 1000, paint);
for (ArrayList<Integer> iter : playerOneRed) {
canvas.drawLine(iter.get(0), iter.get(1), iter.get(2), iter.get(3), paint);
}
}
public void move() {
playerOneRed.add(new ArrayList<Integer>(4));
playerOneRed.get(index).add(0);
playerOneRed.get(index).add(1000);
playerOneRed.get(index).add(x + 250);
x = x + 250;
playerOneRed.get(index).add(1000);
index++;
Invalidate();
}
}