留住片段与自定义视图 [英] Retaining Fragment with Custom View

查看:173
本文介绍了留住片段与自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个小动画项目。我有,关于屏幕的方向转变,这是崩溃的问题。但我想通了,所以在这里张贴整个code的情况下,有人需要类似的东西。在底部的最后一句解释了一个小问题,我观察到的。

I am writing a small animation project. I was having the issue that on screen orientation change, it was crashing. But I figured it out, so posting whole code here in the case someone needs something similar. Last sentence at the bottom explains a small issue I observed.

在这个项目中,我有托管片段主要活动。而片段冲水自定义泡沫视图(泡泡扩展视图)。

In this project, I have main activity hosting a fragment. And the fragment is hosing a custom Bubble view (Bubble extends View).

主要业务布局activity_main.xml中是:

Main activity layout activity_main.xml is:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/bubble_fragment">

</LinearLayout> 

,和主要活动MainActivity.java是:

, and main activity MainActivity.java is:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String tag = "bubble_fragment_tag";
        FragmentManager fm = getFragmentManager();
        if (fm.findFragmentByTag(tag) == null){
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            BubbleFragment bubbleFragment = new BubbleFragment();
            ft.add(R.id.bubble_fragment, bubbleFragment, tag);
            ft.commit();
        }
    }
}

所以,我的主要活动主机在它的自定义视图片段。片段布局bubble_fragment.xml是:

So, my main activity host a fragment with custom view in it. The fragment layout bubble_fragment.xml is:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#ffcc33">

    <study.android.dino.testsolar.Bubble
        android:id="@+id/bubbleAnimationView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff1122"
        android:padding="20dp"/>

    <!-- since parent is FrameLayout, this view will be stacked up in z-order -->
    <LinearLayout
        android:id="@+id/buttonsView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="right|bottom"
        android:layout_margin="10dp">

        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:background="@null"/>
        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:background="@null"/>
        <ImageButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:background="@null"/>
    </LinearLayout>
</FrameLayout>

,我的BubbleFragment.java文件是:
更新:这是更新BubbleFragment能解决问题。

, and my BubbleFragment.java file is: UPDATE: This is updated BubbleFragment that resolves the problem

public class BubbleFragment extends Fragment {

    View view;
    Bubble bubble;
    FrameLayout parent;
    LinearLayout floater;


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        if (bubble == null){
            view =  inflater.inflate(R.layout.bubble_fragment, container, false); 
            parent = (FrameLayout) view;
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onAttach(Activity activity){
        super.onAttach(activity);

        if (parent != null){
            parent.addView(bubble);
            parent.addView(floater);
        }
    }

    @Override
    public void onDetach(){
        super.onDetach();
        bubble = (Bubble) view.findViewById(R.id.bubbleAnimationView);
        floater = (LinearLayout) parent.findViewById(R.id.buttonsView);
        parent.removeView(bubble);
        parent.removeView(floater);
    }
}

这个片段保存自定义视图泡沫这仅仅是一个泡沫在画布上画画是不是在这里很重要;因此不饱满code为它提供了:

This fragment holds custom view Bubble which is just a bubble drawing on Canvas and is not important here; hence not full code for it provided:

public class Bubble extends View {

    private static final boolean BUBBLING = true; //thread is running to draw

    private Paint paint;
    private ShapeDrawable bubble;

    // coordiantes, radius etc
    private int x;
    private int y;
    private int dx;
    private int dy;
    private int r;
    private int w = 400;
    private int h = 400;
    private int speed = 200;

    //handler to invalidate (force redraw on main GUI thread from this thread)
    private Handler handler = new Handler();

    public Bubble(Context context, AttributeSet attributesSet) {
        super(context, attributesSet);

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        w = size.x;
        h = size.y;

        x = w/2;
        y = h/2;
        r = 60;
        dx = 1;
        dy = 1;

        bubble = new ShapeDrawable(new OvalShape());
        bubble.getPaint().setColor(Color.RED);
        bubble.setBounds(0, 0, r, r);

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(10);
    }

    @Override
    protected void onSizeChanged  (int w, int h, int oldw, int oldh){
        //set bubble parameters (center, size, etc)

        startAnimation();
    }

    public void startAnimation(){
        new Thread(new Runnable() {
            public void run() {
                while (BUBBLING) {
                    moveBubble();

                    try {
                        Thread.sleep(speed);
                    } catch (InterruptedException e) {

                    }

                    //update by invalidating on main UI thread
                    handler.post(new Runnable() {
                        public void run() {
                            invalidate();
                        }
                    });
                }
            }
        }).start();
    }


    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        // draws bubble on canvas
        canvas.translate(dx, dy);
        bubble.draw(canvas);
        canvas.restore();
    }

    private void moveBubble(){
        dx += 1;
        dy += 1;
        x = x + dx;
        y = y + dy;
        if (bubble.getPaint().getColor() == Color.YELLOW){
            bubble.getPaint().setColor(Color.RED);
        } else {
            bubble.getPaint().setColor(Color.YELLOW);
        }
    }
}

这所有的作品和我泡平在屏幕上移动和方向的工作也是如此。我观察到的只是小问题是指泡绘制设置为200ms的按code以上的速度。然而,当我改变方向,泡沫闪烁速度虽然跟踪code唾骂这个速度仍然是200。不知道为什么会发生。

This all works and my bubble draws and moves on the screen and orientation works as well. The only 'small' issue I observed is that speed at which bubble is drawn is set to 200ms as per code above. However, when I change orientation, the bubble is blinking faster although tracing code reviled that speed is still 200. Not sure why that is happening.

感谢

推荐答案

我更新了我原来的职位,以显示解决方案。

I updated my original post to show solution.

这篇关于留住片段与自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆