我正在使用 RelativeLayout
绝对定位一些标准 View (如 TextView
)。
我想做的是使用绘制的 Canvas.drawLine
在此 RelativeLayout
的 Canvas
上绘制一条自定义线在所有其他 subview 之后。
这些其他 subview 是通过显式定义 RelativeLayout.LayoutParams
添加的,但我想将在何处绘制自己的决定留给我的自定义行。 p>
我尝试用重载的 View.onDraw(Canvas canvas)
方法将这一行包裹在 CustomView 中,并简单地添加 View 而不 指定任何 LayoutParams
,所以:
public class CustomView extends View {
public CustomView(Context context, int x0, int y0, int x1, int y1) {
super(context);
setClickable(false);
setBackgroundColor(Color.TRANSPARENT);
}
public void onDraw(Canvas canvas) {
Log.i("myapp", "i'm not called! :(")
Paint p = new Paint();
p.setColor(Color.BLACK);
canvas.drawLine(x0, y0, x1, y1, p);
}
}
和用法:
CustomView v = new CustomView(MyActivity.this, 0, 0, 100, 100);
relativeLayout.addView(v);
...但是此onDraw
方法从未被调用。
有没有办法让它工作?
编辑:如果我替换则有效:
relativeLayout.addView(v)
与
relativeLayout.addView(v,
new RelativeLayout.LayoutParams(SOME_WIDTH, SOME_HEIGHT));
重点是,我当时既不知道SOME_WIDTH
,也不知道SOME-HEIGHT
。
最佳答案
试试这个自定义的 RelativeLayout:
class RL extends RelativeLayout {
private Paint mPaint;
public RL(Context context) {
super(context);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStrokeWidth(5);
mPaint.setColor(0xffffffff);
}
@Override
protected void dispatchDraw(Canvas canvas) {
int cnt = getChildCount();
for (int i = 0; i < cnt; i++) {
View child = getChildAt(i);
int l = child.getLeft();
int t = child.getTop();
int r = child.getRight();
int b = child.getBottom();
if (i % 2 == 0) {
canvas.drawLine(l, t, r, b, mPaint);
} else {
canvas.drawLine(l, b, r, t, mPaint);
}
}
super.dispatchDraw(canvas);
}
}
并在 onCreate() 方法中添加以下内容进行测试:
RelativeLayout rl = new RL(this);
TextView tv;
List<String> list = Arrays.asList("one", " two ", "three", " four ", "fife");
int i = 0;
for (String string : list) {
int id = 1000 + i;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (i != 0) {
params.addRule(RL.BELOW, id - 1);
}
tv = new TextView(this);
tv.setTextSize(48);
tv.setTextColor(0xffff0000);
tv.setText(string);
rl.addView(tv, params);
tv.setId(id);
i++;
}
setContentView(rl);
关于android - 在所有其他 View 后面绘制 RelativeLayout Canvas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720101/