2012-03-19 47 views
3

我创建了一个自定义视图,在屏幕上绘制一条线。该视图包括在片段的XML布局和像片段的onCreateView方法如下获得:Android - 在片段中不能工作的自定义视图onResume()

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在听者一切一切正常。

然而,当我在片段的onResume()方法中调用mMyCustomView.drawLine时,虽然它是相同的变量和方法,但没有任何反应。

我能想到的唯一原因是当用户与片段进行交互时,监听器调用该方法,甚至比调用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(); 
} 

} 

当我打电话的onResume() addLine(...)时,则不绘制线条,即使已达到onDraw()方法中for循环的内部。当我在监听器类(它响应某些用户交互)后面添加另一行时,两行都在画布上绘制。不知怎的,canvas.drawLine()在视图的父代片段的onResume()中不起作用。

编辑2

我添加了一个处理程序,调用自定义视图的invalidate方法在反复的片段已经被添加到父活动的布局。该线仍然没有被绘制!

+0

我也试着在onFocusChangeListener的'onFocusChanged'方法中调用drawLine方法,但是这也不起作用。没有人有线索吗? – Schnodahipfe 2012-03-27 18:08:11

+0

你提到过哪一位听众?你能粘贴代码吗?还有,什么是drawline正在做的事情? – Korbi 2012-04-16 18:12:23

回答

3

最后,我通过创建一个处理程序解决了这个问题,该程序在添加片段后50毫秒后调用addLine方法。一个很肮脏的解决方案,但它的工作原理...

相关问题