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但没有解释原因.
有人可以帮帮我吗?
| 归档时间: |
|
| 查看次数: |
959 次 |
| 最近记录: |