編輯:關於Android編程
覺得跟之前的模擬小火箭很相似,又有學習的地方,能作為知識補充。所以轉載一起學習。大家也可以關注他的文章哦。

也就是,用戶可以隨心所欲的拖動控件,布局文件很簡單就是一個Button控件:
android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent">
MainActivity.java:
package com.example.administrator.followview;
public class MainActivity extends Activity implements View.OnTouchListener {
private Button mButton;
private ViewGroup mViewGroup;
private int xDelta;
private int yDelta;
public static final String TAG = "YAYUN";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewGroup = (ViewGroup) findViewById(R.id.root);
mButton = (Button) findViewById(R.id.id_text);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 50;
layoutParams.topMargin = 50;
mButton.setLayoutParams(layoutParams);
mButton.setOnTouchListener(this);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
final int x = (int) event.getRawX();
final int y = (int) event.getRawY();
Log.d(TAG, "onTouch: x= " + x + "y=" + y);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view
.getLayoutParams();
xDelta = x - params.leftMargin;
yDelta = y - params.topMargin;
Log.d(TAG, "ACTION_DOWN: xDelta= " + xDelta + "yDelta=" + yDelta);
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
int xDistance = x - xDelta;
int yDistance = y - yDelta;
Log.d(TAG, "ACTION_MOVE: xDistance= " + xDistance + "yDistance=" + yDistance);
layoutParams.leftMargin = xDistance;
layoutParams.topMargin = yDistance;
view.setLayoutParams(layoutParams);
break;
}
mViewGroup.invalidate();
return true;
}
}
MainActivity實現了OnTouchListener接口,覆寫了onTouch方法,每次回調這個方法通過x和y變量記錄當前的坐標。
ACTION_DOWN是在按下的時候調用(沒抬起來只調用一次),通過xDelta和yDelta來記錄第一次按下的點相對於控件左上角的位置,也就是相對距離。
ACTION_MOVE移動的時候不斷調用,通過xDistance和yDistance來記錄移動的相對距離作為leftMargin和topMargin再動態設置給控件。
最後,調用invalidate方法更新控件位置。
解釋起來不容易解釋,理解起來也不容易理解,我們可以看一下Log,幫助理解:

按下的時候,首先打印當前的坐標為(131,75),由於在onCreate方法中設置了初始的leftMargin和topMargin都為50,所以此時xDelta的值為131-50=81,yDelta的值為75-50=25。第一個ACTION_MOVE的xDistance為132-81=51,yDistance的值為80-25=55,同理,後面都是循環調用了。
這裡主要要注意相對的概念,計算的都是相對距離。
這個效果直接用到的場景不多,但是裡面的處理思路都是在開發中經常會用到的,onTouch方法也是控件交互經常會用到的方法,這方面要很熟悉。
希望這個簡單的實例可以給大家帶來思維的碰撞。
Android-AlertDialog各種對話框的用法
目標效果: 程序運行,顯示圖一的幾個按鈕,點擊按鈕分別顯示圖二到圖六的對話框,點擊對話框的某一項或者按鈕,也會顯示相應的吐司輸出。 1.activity_
Android 中查看內存的使用情況集常用adb命令
1. 在IDE中查看Log信息 當程序運行垃圾回收的時候,會打印一條Log信息,其格式如下: D/dalvikvm: , , , GC_Reason表
Android最佳實踐之Notification、下拉刷新、內存及性能建議等
Notification通知參考地址:http://developer.android.com/training/notify-user/index.html通知(Not
Android SpannableString淺析
引言在應用程序開發過程經常需要對文本進行處理,比如說對一段描述文字的其中一段加入點擊事件,或者對其設置不一樣的前景色,有什麼方法可以實現要求的功能吶?需求樣例比如我們需要