Android自定義View實(shí)現(xiàn)隨手勢滑動控件

本文控件為大家分享了Android隨手勢滑動控件的具體代碼,供大家參考,具體內(nèi)容如下

創(chuàng)新互聯(lián)建站主要從事成都網(wǎng)站建設(shè)、網(wǎng)站制作、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)興城,10余年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792

1.新建自定義控件類:MyView

public class MyView extends Button{
//記錄上次滑動后的坐標(biāo)值
private int lastX;
private int lastY;

public MyView(Context context) {
  super(context);
  // TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs){

  super(context, attrs);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
  // 獲取view相對于手機(jī)屏幕的xy值
  int x=(int) event.getRawX();
  int y=(int) event.getRawY();
  switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:

      break;
    case MotionEvent.ACTION_MOVE:
      int deltaX=x-lastX;
      int deltaY=y-lastY;
      int translationX = (int) (ViewHelper.getTranslationX(this) + deltaX);
      int translationY = (int) (ViewHelper.getTranslationY(this) + deltaY);
      ViewHelper.setTranslationX(this,translationX);
      ViewHelper.setTranslationY(this,translationY);

      break;
    case MotionEvent.ACTION_UP:
      break;
    default:
      break;
  }
  lastX = x;
  lastY = y;
  return true;
}

上面代碼就是一個自定義按鈕類,重寫onTouchEvent()方法來監(jiān)聽用戶滑動,既然說到滑動肯定會存在偏移量的說法。

translationX、translationY是View左上角相對于父布局的偏移量。通過第三方nineoldandroids來實(shí)現(xiàn)動畫滑動。

ViewHelper.getTranslationY(this)計算該View的偏移量,初始值為0,向左偏移值為負(fù),向右偏移值為正。

2.xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
>

 <com.example.administrator.slide.MyView
   android:id="@+id/myview"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="我可以滑動"/>

</RelativeLayout>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前文章:Android自定義View實(shí)現(xiàn)隨手勢滑動控件
轉(zhuǎn)載源于:http://muchs.cn/article0/jcjcio.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、服務(wù)器托管、App設(shè)計、做網(wǎng)站、網(wǎng)站制作、軟件開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司