Android - Custom view in fragment not working in onResume ()
I created a custom view to draw a string on the screen. This view is included in the xml fragment layout and is retrieved as follows in a method 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);
...
}
When I pass the variable mMyCustomView
to the custom listener in the fragment method onCreateView
and call something like mMyCustomView.drawLine
in the listener class everything works fine.
When I call mMyCustomView.drawLine
in a method onResume()
, however nothing happens even though it is the same variable and method.
The only reason I could think of is that the listener calls the method when the user interacts with the fragment, which is even later than what onResume()
is called in relation to the lifecycle. However, inside a fragment, I cannot call the method no later than onResume()
AFAIK.
EDIT 1 :
This is what my custom view looks like:
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();
}
}
When I call addLine (...) on onResume()
, the line is not drawn even though the inside of the for loop in the method is onDraw()
reached. When I add another line later in the listener class (which responds to some user interaction), both lines are drawn to the canvas. Somehow it does canvas.drawLine()
n't work in the onResume()
parent view fragment.
EDIT 2 :
I added a handler that repeatedly calls the custom view method invalidate
after adding a fragment to the parent activity layout. The line is still not drawn!
source to share