主页面
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_myview = findViewById(R.id.main_myview);
edit_score = findViewById(R.id.edit_score);
edit_name =findViewById(R.id.edit_name);
Button btn_add=findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String score = edit_score.getText().toString();
String name = edit_name.getText().toString();
int cj = Integer.parseInt(score);
user = new User(cj, name);
Toast.makeText(MainActivity.this, user.toString()+"",Toast.LENGTH_SHORT).show();
main_myview.addUser(user);
}
});
}
自定义view
public class MyView extends View {
private static final String TAG = "MyView";
private Paint mLinePaint,mTextPaint,mRectPaint;
private List<User> list=new ArrayList<>();
private User user;
private View view;
private EditText edit_score;
private EditText edit_name;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init() {
mLinePaint = new Paint();
mLinePaint.setColor(Color.BLUE);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setStrokeWidth(2);
mRectPaint = new Paint();
mRectPaint.setColor(Color.RED);
mRectPaint.setStyle(Paint.Style.FILL);
mTextPaint = new Paint();
mTextPaint.setColor(Color.BLUE);
mTextPaint.setStyle(Paint.Style.STROKE);
mTextPaint.setTextSize(30);
}
public void addUser(User user) {
if(user!=null){
list.add(user);
this.invalidate();//刷新
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//坐标轴
canvas.drawLine(100,500,500,500,mLinePaint);
canvas.drawLine(100,100,100,500,mLinePaint);
//初始化数据
//坐标
for (int i = 0; i <5; i++) {
int a=i*100;
canvas.drawText(a+"",25,500-100*i,mTextPaint);
}
for (int i = 0; i <list.size() ; i++) {
canvas.drawText(list.get(i).getName(),100+25+100*i,550,mTextPaint);
Log.d(TAG, "onDraw: +++++++"+i);
}
//填充
for (int i = 0; i <list.size() ; i++) {
Rect rect = new Rect();
int a=i*100;
rect.left=100+25+a;
rect.right=100+100+a;
rect.bottom=500;
rect.top=rect.bottom-list.get(i).getScore();
canvas.drawRect(rect,mRectPaint);
}
}
}