刷新时,Android自定义视图会移回原始位置

Ant*_*per 5 java android android-custom-view android-layout android-studio

我正在实现一个时间选择器,如下所示:

未完成的时间选择器

那个黄色的块是MyCustomView.移动时MyCustomView,我应该计算新的日期和设置tvDate.

部分布局文件:

<LinearLayout 
    android:orientation="vertical">

    <TextView android:id="@+id/tv_date">

    <RelativeLayout 
        android:id="@+id/rl">

        <MyCustomView
         android:layout_centerInParent="true"/>

        <OtherViews/>
    </RelativeLayout>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

码:

class MyCustomView extends View{

    // move listener
    public interface IMoveCallback{
        void update(int index);
    }

    private IMoveCallback listener = null; 

    // set listener
    public void setMoveCallback(IMoveCallback callback){
        this.listener = callback;
    }

    @Override
    protected void onDraw(Canvas c){
        super.onDraw(c);
        // draw yellow block and four arrows here.
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        processDrag(v, event);
        invalidate();
        return false;
    }

    private void processDrag(View v, MotionEvent event){
        // calculate new position(left, top, right, bottom)
        v.layout(newLeft, newTop, newRight, newBottom); 
        if(listener != null){
            // calculate index by new position
            listener.update(index);
        }
    }
}

class MainActivity extends Activity implements MyCustomView.IMoveCallback{

    MyCustomView view; // view.setMoveCallback(MainActivity.this)

    @Override
    public void update(int index){
        tvDate.setText(String.valueOf(System.currentTimeMillis()))//update tvDate
    }
}
Run Code Online (Sandbox Code Playgroud)

如果tvDate.setText()删除,请MyCustomView按照手指,如下所示:

在此输入图像描述

如果我更新tvDate,请MyCustomView回到以下位置rl:

在此输入图像描述

我不认为这是一个活动 - 生命周期问题.有人提到((MarginLayoutParams)rl.getLayoutParams()).topMargin但没有解释原因.
有人可以帮帮我吗?

Zai*_*shi 0

您需要保存视图的位置,并在活动恢复(从家里回来)或开始(按返回后返回)时在同一位置渲染它。此图片显示了您可以覆盖以实现此目的的方法,例如失去焦点时的 onPause 等。

编辑

看样子,已经恢复到原来的状态了。发布更多有关如何设置位置等的信息。如果这是您正在移动的视图。然后实现拖动侦听器而不是该更新。让我知道结果如何。