【发布时间】:2016-06-23 07:20:58
【问题描述】:
我正在实现一个时间选择器,如下所示:
那个黄色方块是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>
代码:
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
}
}
如果tvDate.setText() 被移除,MyCustomView 会跟随手指,如下所示:
如果我更新tvDate,MyCustomView 会移回rl 的中心:
我认为这不是活动生命周期问题。有人提到((MarginLayoutParams)rl.getLayoutParams()).topMargin,但没有解释原因。
有人可以帮帮我吗?
【问题讨论】:
-
你应该更具体。 “原来的位置”是什么意思?
-
还显示活动的完整代码。这可能是一个活动生命周期问题
-
@FarhadFaghihi 我已经编辑了我的问题。
MainActivity包含onCreate和回调。我不认为这是一个活动生命周期问题。
标签: java android android-layout android-studio android-custom-view