在Fragment From Activity中设置画布对象的动画

时间:2015-09-28 19:26:03

标签: android android-fragments canvas

好吧,我有一个Activity分为4个片段,在topMost片段中,我使用画布使用Path绘制一个三角形。

在中间片段我有一个视图寻呼机,我正在寻找一种方法来从viewPager onPageScrolled()动画三角形。 代码

片段

public class LoginTopCanvas extends Fragment {
private View topCanvasView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    topCanvasView = new PagerCanvasTop(getActivity());
    return topCanvasView;
}

}

帆布

public class PagerCanvasTop extends View {
private String TAG = "PagerCanvasTop";
Paint redPaint;
Canvas canvas;
public PagerCanvasTop(Context context) {
    super(context);
}
@Override
protected void onDraw(Canvas canvas) {
    this.canvas = canvas;
    canvas.drawColor(getResources().getColor(R.color.bb_red));

    Paint blackPaint = new Paint();
    blackPaint.setColor(getResources().getColor(R.color.bb_black));
    blackPaint.setAntiAlias(true);

    redPaint = new Paint();
    redPaint.setColor(getResources().getColor(R.color.bb_red));
    redPaint.setAntiAlias(true);
    redPaint.setStyle(Paint.Style.STROKE);
    Paint bluePaint = new Paint();
    bluePaint.setColor(Color.BLUE);

    int screenWidth = this.getWidth();
    int screenHeight = this.getHeight();

    canvas.drawCircle(screenWidth / 2, -((screenWidth * 2) - (screenWidth / 15)), (screenWidth * 2), blackPaint);

    //Triangle


    float mid = getWidth() / 2;
    float min = Math.min(getWidth(), getHeight());
    float fat = min / 17;
    float half = min / 2;

    redPaint.setStrokeWidth(fat);
    redPaint.setStyle(Paint.Style.STROKE);
    redPaint.setStyle(Paint.Style.FILL);
    drawTriangle(mid, 35, half - 10, 30, 0);
    canvas.drawCircle(mid, half - 10, 2, bluePaint);
    canvas.drawCircle(mid-35, half+15, 2, bluePaint);
    canvas.drawCircle(mid + 35, half + 15, 2, bluePaint);



    super.onDraw(canvas);

}

public void drawTriangle(float x, int deltaX, float y, int deltaY, float deltaMove) {

    **//this is the triangle which I want to animate**

    Path path = new Path();
    path.reset();
    path.moveTo(x, y+deltaMove);
    path.lineTo(x - deltaX, y + deltaY);
    path.lineTo(x + deltaX, y + deltaY);
    path.close();
    canvas.drawPath(path, redPaint);

}
}

活动

在活动中我有一个带有addOnPageChangeListener的视图寻呼机。从PageScrolled()我想要绘制绘制的traingle动画。我将如何访问画布中绘制的对象,该对象位于myactivty

的片段中

直接调用drawTriangle()并传递一个新的Canvas()给我一个NullpointerException

需要帮助和建议 谢谢

1 个答案:

答案 0 :(得分:0)

您的中间片段应在OnPageChangeListener上设置ViewPager,而不是在onPageScrolled中调用活动的接口方法。

您的活动应实现一些页面滚动界面。您可以创建自己的自定义界面,也可以只重用OnPageChangeListener界面。实现应该引用您的顶部片段(在创建它之后保存引用或调用FragmentManager.findFragmentByTag())并调用顶部片段上的方法来设置onPageScrolled值。

您的顶部片段应该定义一个类似于onPageScrolled的方法,它可以接受活动中的页面滚动值并存储它,然后在片段的视图上调用invalidate()

您的顶部片段应该具有private float mPosition之类的属性,用于存储最后一个位置值。

然后在您的顶部片段onDraw中,绘制三角形时请参阅mPosition属性。