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(;


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()


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) {


public ConnectionLinesView(Context context, AttributeSet attrs) { 
    super(context, attrs);


public ConnectionLinesView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);


protected void onDraw(Canvas canvas) {
    // If lines were already added, draw them
        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;


public void removeLines() {



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

1 answer

I ended up solving the problem by creating a handler that calls the method addLine

after 50 milliseconds after adding the fragment. Pretty messy solution, but it works ...



All Articles