重寫該控件的onTouch方法,move狀態設置該view的margin或者在放手狀態up中設置不需要手勢監聽吧,在該方法中判斷,是down狀態記錄按下的位置,控件移動壹般都是相對布局
解決方案2:
ontounchListener監聽事件
解決方案3:
scroller調用scrollTo
知識點延伸閱讀:
控件平移劃過屏幕(Scroller簡單使用)
MainActivity如下:
package cc.cn;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
/
Demo描述:
Scroller使用示例——讓控件平移劃過屏幕
註意事項:
1 在布局中將cc.cn.LinearLayoutSubClass的控件的寬度設置為"fill_parent"
便於觀察滑動的效果
/
public class MainActivity extends Activity {
private Button mButton;
private LinearLayoutSubClass mLinearLayoutSubClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init(){
mLinearLayoutSubClass=(LinearLayoutSubClass) findViewById(R.id.linearLayoutSubClass);
mButton=(Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mLinearLayoutSubClass.beginScroll();
}
});
}
}
LinearLayoutSubClass如下:
package cc.cn;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.Scroller;
/**
* API註釋:
*
* 1 //第壹,二個參數起始位置;第三,四個滾動的偏移量;第五個參數持續時間
* startScroll(int startX, int startY, int dx, int dy, int duration)
*
* 2 //在startScroll()方法執行過程中即在duration時間內computeScrollOffset()
* 方法會壹直返回true,但當動畫執行完成後會返回返加false.
* computeScrollOffset()
*
* 3 當執行ontouch()或invalidate()或postInvalidate()均會調用該方法
* computeScroll()
*
*/
public class LinearLayoutSubClass extends LinearLayout {
private Scroller mScroller;
private boolean flag=true;
public LinearLayoutSubClass(Context context) {
super(context);
}
public LinearLayoutSubClass(Context context, AttributeSet attrs) {
super(context, attrs);
//也可采用該構造方法傳入壹個interpolator
//mScroller=new Scroller(context, interpolator);
mScroller=new Scroller(context);
}
@Override
public void computeScroll() {
super.computeScroll();
if(mScroller.computeScrollOffset()){
scrollTo(mScroller.getCurrX(), 0);
//使其再次調用computeScroll()直至滑動結束,即不滿足if條件
postInvalidate();
}
}
public void beginScroll(){
if (flag) {
mScroller.startScroll(0, 0, -2500, 0, 2500);
flag = false;
} else {
mScroller.startScroll(0, 0, 0, 0, 1500);
flag = true;
}
//調用invalidate();使其調用computeScroll()
invalidate();
}
}