我创建了一个自定义 View 来在屏幕上画一条线。此 View 包含在 fragment 的 xml 布局中,并在 fragment 的 onCreateView
方法中按如下方式检索:
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
变量传递给 fragment 的 onCreateView
方法中的自定义监听器并在监听器类中调用类似 mMyCustomView.drawLine
的内容时一切正常。
然而,当我在 fragment 的 onResume()
方法中调用 mMyCustomView.drawLine
时,没有任何反应,尽管它是相同的变量和方法。
我能想到的唯一原因是监听器在用户与 fragment 交互时调用该方法,就生命周期而言,这甚至比调用 onResume()
还要晚担心的。但是,在 fragment 中,我不能晚于 onResume()
AFAIK 调用该方法。
编辑 1:
这是我的自定义 View 的样子:
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();
}
}
当我在 onResume()
中调用 addLine(...) 时,即使在 onDraw()
中的 for 循环内部,也不会绘制线条方法达到。当我稍后在监听器类中添加另一行时(响应某些用户交互),两条线都绘制在 Canvas 上。不知何故 canvas.drawLine()
在 View 的父 fragment 的 onResume()
中不起作用。
编辑 2:
我添加了一个处理程序,在将 fragment 添加到父 Activity 的布局后,它会重复调用自定义 View 的 invalidate
方法。线还是画不出来!
最佳答案
最后我通过创建一个处理程序解决了这个问题,该处理程序在添加 fragment 后的 50 毫秒后调用 addLine
方法。一个非常肮脏的解决方案,但它有效......
关于Android - fragment 中的自定义 View 在 onResume() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9774647/