我创建了一个自定义视图来在屏幕上画一条线。onCreateView
此视图包含在片段的 xml 布局中,并在片段的方法中检索如下:
MyCustomView mMyCustomView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate view
View v = inflater.inflate(R.layout.fragment, container, false);
mMyCustomView = (MyCustomView) v.findViewById(R.id.my_custom_view);
...
}
当我将mMyCustomView
变量传递给片段onCreateView
方法中的自定义侦听器并在侦听器类中调用类似的东西mMyCustomView.drawLine
时,一切正常。
然而,当我调用mMyCustomView.drawLine
片段的onResume()
方法时,没有任何反应,尽管它是相同的变量和方法。
我能想到的唯一原因是,当用户与片段交互时,侦听器调用该方法,onResume()
就生命周期而言,这甚至比被调用的还要晚。但是,在片段中,我不能在onResume()
AFAIK 之后调用该方法。
编辑 1:
这是我的自定义视图的样子:
public class ConnectionLinesView extends View {
// Class variables
Paint mPaint = new Paint(); // Paint to apply to lines
ArrayList<float[]> mLines = new ArrayList<float[]>(); // Array to store the lines
public ConnectionLinesView(Context context) {
super(context);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(2);
}
public ConnectionLinesView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(2);
}
public ConnectionLinesView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(2);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// If lines were already added, draw them
if(!mLines.isEmpty()){
for(float[] line : mLines){
canvas.drawLine(line[0], line[1], line[2], line[3], mPaint);
}
}
}
// Method to add a line to the view
public void addLine(View v1, View v2) {
float[] line = new float[4];
line[0] = v1.getX() + v1.getWidth()/2;
line[1] = v1.getY() + v1.getHeight()/2;
line[2] = v2.getX() + v2.getWidth()/2;
line[3] = v2.getY() + v2.getHeight()/2;
mLines.add(line);
this.invalidate();
}
public void removeLines() {
mLines.clear();
this.invalidate();
}
}
当我调用 addLine(...) inonResume()
时,即使onDraw()
到达方法中 for 循环的内部,也不会绘制线。当我稍后在侦听器类(响应某些用户交互)中添加另一条线时,两条线都绘制在画布上。不知何故,在视图的父片段中 canvas.drawLine()
不起作用。onResume()
编辑 2:
I have added a handler, that calls the custom view's invalidate
method repeatedly after the fragment has been added to the layout of the parent activity. The line still doesn't get drawn!