为了账号安全,请及时绑定邮箱和手机立即绑定

android 在屏幕中随意拖拽摆放控件 工具栏划出效果

标签:
Android

package com.example.customnavbar;

import java.util.ArrayList;

import java.util.List;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.AlertDialog;

import android.app.Service;

import android.content.DialogInterface;

import android.graphics.Bitmap;

import android.graphics.PixelFormat;

import android.graphics.drawable.Drawable;

import android.os.Bundle;

import android.os.Vibrator;

import android.util.DisplayMetrics;

import android.util.Log;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnLongClickListener;

import android.view.View.OnTouchListener;

import android.view.ViewGroup;

import android.view.ViewGroup.LayoutParams;

import android.view.WindowManager;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.RelativeLayout;

import android.widget.Toast;

@SuppressLint("NewApi")

public class MainActivity extends Activity {

/**可以自定义的按钮:破事*/

public static final String badthing = "badthing";

/**可以自定义的按钮:内涵*/

public static final String connotation = "connotation";

/**可以自定义的按钮:妹纸*/

public static final String girl = "girl";

/**可以自定义的按钮:漫画*/

public static final String cartoon = "cartoon";

/**可以自定义的按钮:热门(综合)*/

public static final String hotComment = "hotComment";

/**上方图片触摸监听*/

private OnTouchListener touchListener;

/**菜单导航栏拖拽监听*/

//private OnTouchListener MenutouchListener;

/**标记*/

private String tag = "";

/**用于记录当前没有在菜单栏的Button*/

private String buttonstr = "";

/**用于记录菜单栏的布局情况*/

private List<String> RecordMenu = new ArrayList<String>();

/**上方图片拖拽时的临时控件*/

private ImageView dragImageView;

/**手机屏幕的宽度*/

private int screenWidth;

/**手机屏幕的高度*/

private int screenHeight;

/**拖拽图片的宽度*/

private int dragViewWidth;

/**拖拽图片的高度*/

private int dragViewHeight;

float density=1;

int densitys=50;

/**上方拖拽图片区域布局*/

private LinearLayout llLayout;

private Button iv_building,iv_jzx, door,doorVertical;

private WindowManager windowManager;

private WindowManager.LayoutParams windowParams;

private List<Button> imgs=new ArrayList<Button>();

RelativeLayout rl;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.custom_navbar);

rl=(RelativeLayout) findViewById(R.id.Custom_layout);

iv_building=(Button) findViewById(R.id.building);

iv_building.setTag(1+"");

iv_jzx=(Button) findViewById(R.id.gjx);

iv_jzx.setTag(2+"");

door=(Button) findViewById(R.id.door);

door.setTag(3+"");

doorVertical=(Button) findViewById(R.id.door2);

doorVertical.setTag(4+"");

DisplayMetrics dm2 = getResources().getDisplayMetrics();

screenHeight = dm2.heightPixels;

screenWidth = dm2.widthPixels;

density=dm2.density;

   Log.i("test", screenHeight+";"+screenWidth+";"+dm2.density);

touchListener = new OnTouchListener() {

@Override

public boolean onTouch(View v, MotionEvent event) {

switch(event.getAction()){

case MotionEvent.ACTION_DOWN: //手指按下时操作

//记录手指按下的坐标

int x = (int) event.getRawX();

int y = (int) event.getRawY();

dragViewWidth = v.getWidth();

dragViewHeight = v.getHeight();

int t = (int)((Integer.valueOf((String) v.getTag())));

v.setDrawingCacheEnabled(true);

Bitmap bitmap = v.getDrawingCache();

startDrag(bitmap, x, y,t);

//setViewDrag(v,true);

Log.i(tag, tag + " x="+event.getRawX()+" y="+event.getRawY());

break;

case MotionEvent.ACTION_MOVE:  //手指移动时操作

int moveX = (int)event.getRawX();

int moveY = (int)event.getRawY();

onDrag(moveX,moveY);

break;

case MotionEvent.ACTION_UP:   //手指放开时操作

int UpX = (int)event.getRawX();

int UpY = (int)event.getRawY();

int t1 = (int)((Integer.valueOf((String) v.getTag())));

stopDrag(UpX,UpY,t1);

break;

}

return false;

}

};

iv_jzx.setOnTouchListener(touchListener);

iv_building.setOnTouchListener(touchListener);

door.setOnTouchListener(touchListener);

doorVertical.setOnTouchListener(touchListener);

}

/**生成拖拽的影像*/

private void startDrag(Bitmap btp,int x ,int y,int tag){

if(btp == null) return;

windowManager = (WindowManager)this.getSystemService(WINDOW_SERVICE);

ImageView imageView = new ImageView(MainActivity.this);

imageView.setLayoutParams(new LinearLayout.LayoutParams(btp.getWidth(),btp.getHeight()));

windowParams = new WindowManager.LayoutParams();

windowParams.gravity = Gravity.LEFT|Gravity.TOP;

windowParams.x = x - dragViewWidth;

windowParams.y = y - dragViewHeight;

windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;

windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

windowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE

| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE

| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON

| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;

windowParams.format = PixelFormat.TRANSLUCENT;

//windowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT | WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;

windowParams.windowAnimations = 0;

imageView.setImageBitmap(btp);

windowManager.addView(imageView, windowParams);

dragImageView = imageView;

}

@SuppressLint("ClickableViewAccessibility")

OnTouchListener imgOnTouchListener=new OnTouchListener() {

int lastX, lastY;

         int downX,downY;

         long beginTime=0,endTime=0;

@Override

public boolean onTouch(View v, MotionEvent event) {

int ea=event.getAction();

Log.i("TAG", "Touch:"+ea);

//Toast.makeText(DraftTest.this, "λ�ã�"+x+","+y, Toast.LENGTH_SHORT).show();

switch(ea){

case MotionEvent.ACTION_DOWN:

beginTime=System.currentTimeMillis();

lastX = (int) event.getRawX();

lastY = (int) event.getRawY();

downX=lastX;

downY=lastY;

Log.i("test", "ACTION_DOWN");

break;

/**

 * layout(l,t,r,b)

 * l  Left position, relative to parent 

                t  Top position, relative to parent 

                r  Right position, relative to parent 

                b  Bottom position, relative to parent  

 * */

case MotionEvent.ACTION_MOVE:

int dx =(int)event.getRawX() - lastX;

int dy =(int)event.getRawY() - lastY;

int left = v.getLeft() + dx;

int top = v.getTop() + dy;

int right = v.getRight() + dx;

int bottom = v.getBottom() + dy;

if(left < 0){

left = 0;

right = left + v.getWidth();

}

if(right > screenWidth){

right = screenWidth;

left = right - v.getWidth();

}

if(top < 0){

top = 0;

bottom = top + v.getHeight();

}

if(bottom > screenHeight){

bottom = screenHeight;

top = bottom - v.getHeight();

}

v.layout(left, top, right, bottom);

Log.i("test", "position��" + left +", " + top + ", " + right + ", " + bottom);

lastX = (int) event.getRawX();

lastY = (int) event.getRawY();

//endTime=System.currentTimeMillis();

/*if(Math.abs(lastX-downX)<=8 && Math.abs(lastY-downY)<=8 && endTime-beginTime>2000){//长按

  Vibrator vib = (Vibrator)MainActivity.this.getSystemService(Service.VIBRATOR_SERVICE);  

          //  vib.vibrate(250);//只震动一秒,一次  

            long[] pattern = {0,250};  

            //两个参数,一个是自定义震动模式,  

            //数组中数字的含义依次是静止的时长,震动时长,静止时长,震动时长。。。时长的单位是毫秒  

            //第二个是“是否反复震动”,-1 不重复震动   0:重复震动

            //第二个参数必须小于pattern的长度,不然会抛ArrayIndexOutOfBoundsException  

            vib.vibrate(pattern, -1);  

//Toast.makeText(MainActivity.this,"长按了"+v.getTag().toString(), Toast.LENGTH_SHORT).show();

chooseDialoge(v);

}*/

break;

case MotionEvent.ACTION_UP:

endTime=System.currentTimeMillis();

lastX = (int) event.getRawX();

lastY = (int) event.getRawY();

if(Math.abs(lastX-downX)>8 ||Math.abs(lastY-downY)>8){//移动

rl.removeView(v);

RelativeLayout.LayoutParams ap=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

int leftMargin=v.getLeft();

int topMargin=v.getTop();

// if(v.getLeft()%densitys<densitys/2){

// leftMargin=v.getLeft()-v.getLeft()%densitys;

// }else{

// leftMargin=v.getLeft()-v.getLeft()%densitys+densitys;

// }

// if(v.getTop()%densitys<densitys/2){

// topMargin=v.getTop()-v.getTop()%densitys;

// }else{

// topMargin=v.getTop()-v.getTop()%densitys+densitys;

// }

ap.setMargins(leftMargin, topMargin, 0, 0);

rl.addView(v, ap);

Toast.makeText(MainActivity.this,"移动了"+v.getTag().toString(), Toast.LENGTH_SHORT).show();

}else {

if(endTime-beginTime>2000){//长按

  /*Vibrator vib = (Vibrator)MainActivity.this.getSystemService(Service.VIBRATOR_SERVICE);  

          //  vib.vibrate(250);//只震动一秒,一次  

            long[] pattern = {0,250};  

            //两个参数,一个是自定义震动模式,  

            //数组中数字的含义依次是静止的时长,震动时长,静止时长,震动时长。。。时长的单位是毫秒  

            //第二个是“是否反复震动”,-1 不重复震动   0:重复震动

            //第二个参数必须小于pattern的长度,不然会抛ArrayIndexOutOfBoundsException  

            vib.vibrate(pattern, -1);  

*/ //Toast.makeText(MainActivity.this,"长按了"+v.getTag().toString(), Toast.LENGTH_SHORT).show();

chooseDialoge(v);

}else{//单击

Toast.makeText(MainActivity.this,"单击了"+v.getTag().toString(), Toast.LENGTH_SHORT).show();

}

}

break;        

}

return true;

}

};

int buildingCount=0,jzxCount=0,doorCount=0;

/***

 * 停止拖动,去掉拖动时候的影像

 */

public void stopDrag(int UpX, int UpY,int tag){

if(UpY>screenHeight-iv_building.getMeasuredHeight()-20){

if(dragImageView != null){

windowManager.removeView(dragImageView);

dragImageView = null;

}

return ;

}

Button bt=new Button(MainActivity.this);

//final ImageView imm=new ImageView(MainActivity.this);

RelativeLayout.LayoutParams rll=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

int leftMargin=UpX - dragViewWidth;

int topMargin=UpY - 3*dragViewHeight-dragViewHeight/2;

// if((UpX - dragViewWidth)%densitys<densitys/2){

// leftMargin=UpX - dragViewWidth-(UpX - dragViewWidth)%densitys;

// }else{

// leftMargin=UpX - dragViewWidth-(UpX - dragViewWidth)%densitys+densitys;

//

// }

// if( (UpY - 3*dragViewHeight-dragViewHeight/2)%densitys<densitys/2){

// topMargin=UpY - 3*dragViewHeight-dragViewHeight/2-(UpY - 3*dragViewHeight-dragViewHeight/2)%densitys;

// }else{

// topMargin=UpY - 3*dragViewHeight-dragViewHeight/2-(UpY - 3*dragViewHeight-dragViewHeight/2)%densitys+densitys;

//

// }

rll.setMargins(leftMargin, topMargin,0, 0);

bt.setLayoutParams(rll);

Drawable homepressed=null;

if(tag==1){

bt.setBackgroundResource(R.drawable.icon_bg);

 homepressed=getResources().getDrawable(R.drawable.icon_building);

buildingCount++;

//imm.setTag(buildingCount+"栋");

//imm.setBackgroundResource(R.drawable.icon_building);

bt.setTag(buildingCount+"栋");

bt.setText(buildingCount+"号楼");

homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());

bt.setCompoundDrawables(null, null, null, homepressed);

}else if(tag==2){

bt.setBackgroundResource(R.drawable.icon_bg);

 homepressed=getResources().getDrawable(R.drawable.icon_gjx);

jzxCount++;

bt.setTag("光交箱"+jzxCount);

bt.setText("光交箱"+jzxCount);

homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());

bt.setCompoundDrawables(null, null, null, homepressed);

}else if(tag==3){

bt.setBackgroundResource(android.R.color.transparent);

 homepressed=getResources().getDrawable(R.drawable.icon_door);

 doorCount++;

bt.setTag("大门"+doorCount);

bt.setText("大门"+doorCount);

homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());

bt.setCompoundDrawables(null, null, null, homepressed);

}else if(tag==4){

bt.setBackgroundResource(android.R.color.transparent);

 homepressed=getResources().getDrawable(R.drawable.icon_door2);

 doorCount++;

bt.setTag("大门"+doorCount);

bt.setText("大门"+doorCount);

homepressed.setBounds(0, 0, homepressed.getMinimumWidth(), homepressed.getMinimumHeight());

bt.setCompoundDrawables(null, null, homepressed, null);

}

bt.setTextSize(13);

bt.setMinHeight(0);

bt.setMinWidth(0);

bt.setOnTouchListener(imgOnTouchListener);

imgs.add(bt);

rl.addView(bt);

//_____________________________

/* StickerView stickerView = new StickerView(this);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

                ViewGroup.LayoutParams.WRAP_CONTENT,

                ViewGroup.LayoutParams.WRAP_CONTENT);*/

//         params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.image);

//         params.addRule(RelativeLayout.ALIGN_TOP, R.id.image);

/* stickerView.setOnLongClickListener(new OnLongClickListener() {

@Override

public boolean onLongClick(View v) {

// TODO Auto-generated method stub

return false;

}

});

        rl.addView(stickerView, rll);

        Bitmap bitmap =  bt.getDrawingCache();

        stickerView.setWaterMark(bitmap);*/

//______________________

if(dragImageView != null){

windowManager.removeView(dragImageView);

dragImageView = null;

}

}

/**实现拖动影像*/

public void onDrag(int x, int y){

if(dragImageView!=null){

windowParams.alpha = 0.8f;

windowParams.x = x - dragViewWidth;

windowParams.y = y - dragViewHeight;

windowManager.updateViewLayout(dragImageView, windowParams);

}

private void editDialoge(final View view){

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setIcon(R.drawable.ic_launcher);

        builder.setTitle("请输入新名称");

        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象

         View view2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialoge_name, null);

        //    设置我们自己定义的布局文件作为弹出框的Content

        builder.setView(view2);

        

        final EditText username = (EditText)view2.findViewById(R.id.username);

        

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()

        {

            @Override

            public void onClick(DialogInterface dialog, int which)

            {

                String a = username.getText().toString().trim();

                //    将输入的用户名和密码打印出来

                Button t=(Button) view;

                t.setText(a);

                t.setTag(a);

            } 

        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()

        {

            @Override

            public void onClick(DialogInterface dialog, int which)

            {

                

            }

        });

        builder.show();

}

private void chooseDialoge(final View v){

  AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

          builder.setIcon(R.drawable.ic_launcher);

          builder.setTitle("选择操作");

          //    指定下拉列表的显示数据

          final String[] cities = {"重命名", "删除"};

          //    设置一个下拉的列表选择项

          builder.setItems(cities, new DialogInterface.OnClickListener()

          {

              @Override

              public void onClick(DialogInterface dialog, int which)

              {

                 // Toast.makeText(MainActivity.this, "选择的城市为:" + cities[which], Toast.LENGTH_SHORT).show();

             if(which==0){

              editDialoge(v);

             }else{

             confirmDialoge(v);

             }

              }

          });

          builder.show();

}

public void confirmDialoge(final View view){

  //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        //    设置Title的图标

        builder.setIcon(R.drawable.ic_launcher);

        //    设置Title的内容

        builder.setTitle("请确认");

        //    设置Content来显示一个信息

        builder.setMessage("确定删除吗?");

        //    设置一个PositiveButton

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()

        {

            @Override

            public void onClick(DialogInterface dialog, int which)

            {

              rl.removeView(view);

             //Toast.makeText(MainActivity.this, "positive: " + which, Toast.LENGTH_SHORT).show();

            }

        });

        //    设置一个NegativeButton

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()

        {

            @Override

            public void onClick(DialogInterface dialog, int which)

            {

                //Toast.makeText(MainActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();

            }

        });

        //    设置一个NeutralButton

       /* builder.setNeutralButton("忽略", new DialogInterface.OnClickListener()

        {

            @Override

            public void onClick(DialogInterface dialog, int which)

            {

                Toast.makeText(MainActivity.this, "neutral: " + which, Toast.LENGTH_SHORT).show();

            }

        });*/

        //    显示出该对话框

        builder.show();

       

}

@Override

protected void onDestroy() {

System.gc();

super.onDestroy();

}

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/Custom_layout"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

           >

             <LinearLayout

                android:id="@+id/PullIcon"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_alignParentBottom="true"

                android:background="@color/shenlan"

                android:gravity="center_vertical"

                android:orientation="horizontal"

                android:padding="8dp" >

                <LinearLayout

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:background="@drawable/white_bg" >

                    <Button

                        android:id="@+id/building"

                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"

                        android:layout_margin="10dp"

                        android:background="@drawable/icon_building"

                        android:minHeight="0dp"

                        android:minWidth="0dp" />

                </LinearLayout>

                <LinearLayout

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_marginLeft="15dp"

                    android:background="@drawable/white_bg" >

                    <Button

                        android:id="@+id/gjx"

                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"

                        android:layout_margin="10dp"

                        android:background="@drawable/icon_gjx"

                        android:minHeight="0dp"

                        android:minWidth="0dp" />

                </LinearLayout>

                <LinearLayout

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_marginLeft="15dp"

                    android:background="@drawable/white_bg" >

                    <Button

                        android:id="@+id/door"

                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"

                        android:layout_margin="7dp"

                        android:background="@drawable/icon_door1"

                        android:minHeight="0dp"

                        android:minWidth="0dp" />

                </LinearLayout>

                <LinearLayout

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_marginLeft="15dp"

                    android:background="@drawable/white_bg" >

                    <Button

                        android:id="@+id/door2"

                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"

                        android:layout_margin="10dp"

                        android:background="@drawable/icon_door2_small"

                        android:minHeight="0dp"

                        android:minWidth="0dp" />

                </LinearLayout>

            </LinearLayout>

       

 </RelativeLayout>

原文链接:http://www.apkbus.com/blog-179843-61670.html

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消