你好,游客 登录 注册 搜索
背景:
阅读新闻

Android上拖放效果的实现

[日期:2011-10-19] 来源:Linux社区  作者:Linux [字体:大 中 小]

实现的效果就是在界面上拖动这一个按钮到处跑。

1 布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
<Button android:id="@+id/btn_hello"
      android:layout_width="fill_parent"
     android:layout_height="wrap_content"
      android:text="@string/hello"/>
</LinearLayout>

代码:

package com.roiding.sample;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button; 
 
public
class Touch extends Activity {
/** Called when the activity is first created. */
@Override
public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); 
 
final Button btn = (Button) findViewById(R.id.btn_hello);
btn.setOnTouchListener(new OnTouchListener() {
int[] temp = new
int[] { 0, 0 };
public
boolean onTouch(View v, MotionEvent event) { 
 
int eventaction = event.getAction();
Log.i("&amp;&amp;&amp;", "onTouchEvent:" + eventaction); 
 
int x = (int) event.getRawX();
int y = (int) event.getRawY(); 
 
switch (eventaction) { 
 
          case MotionEvent.ACTION_DOWN: // touch down so check if the
                    temp[0] = (int) event.getX();
                    temp[1] = y - v.getTop();
                    break; 
 
          case MotionEvent.ACTION_MOVE: // touch drag with the ball
                    v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0], y - temp[1] + v.getHeight());
                    v.postInvalidate();
           break; 
 
          case MotionEvent.ACTION_UP:
                   break;
            }
        return false;
}
});
}
}
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款