您好,登錄后才能下訂單哦!
這篇文章主要介紹“Android怎么實(shí)現(xiàn)通過(guò)單點(diǎn)觸摸移動(dòng)圖片”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“Android怎么實(shí)現(xiàn)通過(guò)單點(diǎn)觸摸移動(dòng)圖片”文章能幫助大家解決問(wèn)題。
編寫布局資源文件
先準(zhǔn)備一張圖片放入drawable內(nèi)
這里主要就是將圖片顯示出來(lái)并設(shè)置id(android:scaleType="fitXY"表示圖片按原比例設(shè)置大?。?/p>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bk019" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:id="@+id/ivImages" android:layout_width="100dp" android:layout_height="120dp" android:scaleType="fitXY" android:src="@drawable/bk031" /> </LinearLayout>
編寫主布局文件
(tag是為了看移動(dòng)圖片時(shí)的數(shù)據(jù))
import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private static final String TAG = "move_images_by_touch"; private ImageView ivImages; private LinearLayout root; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //利用布局資源文件設(shè)置用戶界面 setContentView(R.layout.activity_main); //通過(guò)資源標(biāo)識(shí)符獲取控件實(shí)例 ivImages = findViewById(R.id.ivImages); root = findViewById(R.id.root); //設(shè)置根布局可以獲取焦點(diǎn) root.setFocusable(true); //讓布局獲取焦點(diǎn) root.requestFocus(); //給根布局注冊(cè)完觸摸監(jiān)聽器,實(shí)現(xiàn)觸摸監(jiān)聽器接口,編寫觸摸事件代碼 root.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { //根據(jù)觸摸動(dòng)作執(zhí)行不同的操作 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //觸點(diǎn)按下 Log.d(TAG, "ACTION_DOWN"+event.getX() + "," + event.getY()); break; case MotionEvent.ACTION_MOVE: //觸點(diǎn)移動(dòng) Log.d(TAG, "ACTION_MOVE"+event.getX() + "," + event.getY()); break; case MotionEvent.ACTION_UP: //觸點(diǎn)放開 Log.d(TAG, "ACTION_UP"+event.getX() + "," + event.getY()); break; } //設(shè)置圖像控件坐標(biāo) ivImages.setX(event.getX()-ivImages.getWidth()/2); ivImages.setY(event.getY()-ivImages.getHeight()/2); return true;//設(shè)置為真,三個(gè)事件:down-->move-->up依次執(zhí)行 } }); } }
效果
關(guān)于“Android怎么實(shí)現(xiàn)通過(guò)單點(diǎn)觸摸移動(dòng)圖片”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。