【问题标题】:How to create a layout?如何创建布局?
【发布时间】:2018-05-12 16:13:04
【问题描述】:
我正在尝试在我的 Android 应用程序中显示带有类似于此图片的节点的三角形
而且我只有两个可绘制对象。第一个是圆形的,第二个是直线的。
我在互联网上搜索了很多,但没有找到任何解决方案来解决我应该使用哪种布局以及如何在 Android 上实现显示这个三角形。
我无法拍摄这个三角形的完整图像,因为节点会在运行时显示一些动态数据。
【问题讨论】:
标签:
android
layout
view
drawable
【解决方案1】:
借助 Android Canvas 及其方法 drawLines() 和 drawCircle() 使用自定义视图
这里是创建Custom Views 的方法,这里是一个非常漂亮的简短tutorial,介绍如何使用这些方法绘制任何形状。
样本
// somewhere in the constructor, call this
private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
// mPaint.setStrokeWidth(SOME_VALUE);
...
}
// override onSizeChanged() to make your measurements.
// if you need 'finer' control, override onMeasure(), but be careful with that one
// (read its javadocs before you override it).
// measurements include shape and text locations and sizes, etc.
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mTriangleVertices[0] = 0.2 * w; // x0
mTriangleVertices[1] = 0.15 * h; // y0
mTriangleVertices[2] = 0.5 * w; // x1
mTriangleVertices[3] = 0.85 * h; // y1
mTriangleVertices[4] = 0.8 * w; // x2
mTriangleVertices[5] = 0.15 * h; // y2
// other calculations...
}
// after you save your measurements to some fields, override onDraw().
// use all the tools you created and the info you gathers above here.
// avoid creating objects at all cost. read the docs for more info.
protected void onDraw(Canvas canvas) {
super.onDraw(canvas); // include this first, last or you can even omit it sometimes
canvas.drawLines(mTriangleVertices, 0, mTriangleVertices.length, mPaint);
// canvas.drawCircle(); canvas.drawOval(); etc..
}