怎么在Android中實現(xiàn)一個跟隨手指的小球效果

怎么在Android中實現(xiàn)一個跟隨手指的小球效果?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

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

配置DrawView類用于繪制小球

public class DrawView extends View {
  public float currentX = 40;
  public float currentY = 50;
  //定義并創(chuàng)建畫筆
  Paint p = new Paint();
  public DrawView(Context context)
  {
    super(context);
  }
  public DrawView(Context context , AttributeSet set)
  {
    super(context,set);
  }
  @Override
  public void onDrawForeground(Canvas canvas) {
    super.onDrawForeground(canvas);
    //設置畫筆顏色
    p.setColor(Color.RED);
    //繪制一個小球
    canvas.drawCircle(currentX , currentY , 30 , p);
  }
  //為組建的觸碰實踐重寫處理方法
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    //修改currentX,currentY的兩個屬性
    currentX = event.getX();
    currentY = event.getY();
    //通知當前組建重繪自己
    invalidate();
    //放回true表明該處理方法已經(jīng)處理該事件
    return true;
  }
}

MainActivity

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //獲取Linearlayout布局容器
    LinearLayout root = (LinearLayout) findViewById(R.id.root);
    //創(chuàng)建DrawView組件
    final DrawView draw = new DrawView(this);
    //設定自定義組件的最小寬度、高度
    draw.setMinimumWidth(300);
    draw.setMinimumHeight(500);
    root.addView(draw);
  }
}

xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <com.example.a30797.myapplication.DrawView
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

**注:**由上面布局,已經(jīng)添加了自定義組件,因此Activity代碼可簡化為:

public class MainActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }
}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

分享名稱:怎么在Android中實現(xiàn)一個跟隨手指的小球效果
標題來源:http://bm7419.com/article22/gejejc.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導航、響應式網(wǎng)站微信公眾號、品牌網(wǎng)站制作外貿(mào)網(wǎng)站建設、手機網(wǎng)站建設

廣告

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

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