电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

Android自定義控件實現(xiàn)方向盤效果

瀏覽:3日期:2022-09-24 17:21:45

在很多開發(fā)中,為了界面更加的友好,在自定義View的基礎(chǔ)上,開發(fā)者會開發(fā)出各種各樣的自定義控件來滿足實際開發(fā)需要,其中有一種”方向盤”的控件在實際開發(fā)中非常常見,便于用戶進行一些實際性的方向控制。

在復(fù)習參考了許多自定義控件的基礎(chǔ)上,我實現(xiàn)了一個最最基本的方向盤空間,并且可以根據(jù)方向做出相應(yīng)的反應(yīng)。話不多說,先看看效果。

做的有點丑,大家可以看看實際原理,后期再優(yōu)化具體“方向盤”.

Android自定義控件實現(xiàn)方向盤效果

空間下面的幾行字是我為了確定方向所寫的一些參數(shù),基本思想就是在方向盤的中心確定一個坐標軸,根據(jù)中間這個小圓的和中心點的距離與方向確定所處的方向。在手離開屏幕以后,小圓回到原點。

一言不合就放代碼~~~~

具體是怎么實現(xiàn)的呢??

來我們一起看看代碼,看完一目了然。

package com.sshhsun.socketudp.utils;import android.annotation.SuppressLint;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.util.Log;import android.view.MotionEvent;import android.view.View;public class MyWheel extends View implements Runnable,View.OnTouchListener { public MyWheel(Context context) { super(context); // TODO Auto-generated constructor stub } //先定義一些繪圖要用的基本參數(shù) public static final int BOTTOM = 7; public static final int BOTTOM_LEFT = 8; public static final long DEFAULT_LOOP_INTERVAL = 100L; public static final int FRONT = 3; public static final int FRONT_RIGHT = 4; public static final int LEFT = 1; public static final int LEFT_FRONT = 2; public static final int RIGHT = 5; public static final int RIGHT_BOTTOM = 6; private final double RAD = 57.295779500000002D; private Paint button; private int buttonRadius; public double centerX = 0.0D; public double centerY = 0.0D; private Paint horizontalLine; private int joystickRadius; private int lastAngle = 0; private int lastPower = 0; private long loopInterval = 100L; private Paint mainCircle; //整個控件的大圓,及小紅點的活動范圍 //自定義的接口用于監(jiān)聽處理控件的觸摸事件 private OnMyWheelMoveListener onmywheelMoveListener; private Paint secondaryCircle;//第二個內(nèi)圓,小紅圓超過后開始處理角度 private Thread thread = new Thread(this); private Paint verticalLine; private int xPosition = 0; private int yPosition = 0; private static final String tag='MyWheel'; public MyWheel(Context paramContext, AttributeSet paramAttributeSet) { super(paramContext, paramAttributeSet); initMyWheel(); //好吧,我知道MyWheel這個名字有點太隨便了........ } public MyWheel(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); initMyWheel(); } //根據(jù)所處的位置得到角度 private int getAngle() { if (this.xPosition > this.centerX) { if (this.yPosition < this.centerY) {int m = (int) (90.0D + 57.295779500000002D * Math .atan((this.yPosition - this.centerY)/ (this.xPosition - this.centerX)));this.lastAngle = m;return m; } if (this.yPosition > this.centerY) {int k = 90 + (int) (57.295779500000002D * Math .atan((this.yPosition - this.centerY)/ (this.xPosition - this.centerX)));this.lastAngle = k;return k; } this.lastAngle = 90; return 90; } if (this.xPosition < this.centerX) { if (this.yPosition < this.centerY) {int j = (int) (57.295779500000002D * Math .atan((this.yPosition - this.centerY)/ (this.xPosition - this.centerX)) - 90.0D);this.lastAngle = j;return j; } if (this.yPosition > this.centerY) {int i = -90 + (int) (57.295779500000002D * Math.atan((this.yPosition - this.centerY) / (this.xPosition - this.centerX)));this.lastAngle = i;return i; } this.lastAngle = -90; return -90; } if (this.yPosition <= this.centerY) { this.lastAngle = 0; return 0; } if (this.lastAngle < 0) { this.lastAngle = -180; return -180; } this.lastAngle = 180; return 180; } //根據(jù)紅色圓的距離和角度得到方向 private int getDirection() { int k; int j = 0; int i; if ((this.lastPower == 0) && (this.lastAngle == 0)) { k = 0; return k; } if (this.lastAngle <= 0) j = 90 + -1 * this.lastAngle; while (true) { k = 1 + (j + 22) / 45; if (k <= 8) {break; } if (this.lastAngle <= 90) {j = 90 - this.lastAngle;continue; } j = 360 - (-90 + this.lastAngle); } return k; } //得到紅色圓與中心的距離 private int getPower() { return (this.lastPower=(int) (100.0D * Math.sqrt((this.xPosition - this.centerX)* (this.xPosition - this.centerX)+ (this.yPosition - this.centerY)* (this.yPosition - this.centerY)) / this.joystickRadius)); } private int measure(int paramInt) { int i = View.MeasureSpec.getMode(paramInt); int j = View.MeasureSpec.getSize(paramInt); if (i == 0) return 200; return j; } //初始化一些基本參數(shù) protected void initMyWheel() { this.mainCircle = new Paint(1); this.mainCircle.setColor(Color.BLUE); this.mainCircle.setStrokeWidth(3.0f); this.mainCircle.setStyle(Paint.Style.STROKE); this.secondaryCircle = new Paint(); this.secondaryCircle.setColor(-16711936); this.secondaryCircle.setStrokeWidth(3.0f); this.secondaryCircle.setStyle(Paint.Style.STROKE); this.verticalLine = new Paint(); this.verticalLine.setStrokeWidth(5.0F); this.verticalLine.setColor(-65536); this.horizontalLine = new Paint(); this.horizontalLine.setStrokeWidth(2.0F); this.horizontalLine.setColor(-16777216); this.button = new Paint(1); this.button.setColor(Color.RED); this.button.setStyle(Paint.Style.FILL); } //初始化以后繪制方向盤。 protected void onDraw(Canvas paramCanvas) { this.centerX = (getWidth() / 2); this.centerY = (getHeight() / 2); paramCanvas.drawCircle((int) this.centerX, (int) this.centerY,this.joystickRadius, this.mainCircle); paramCanvas.drawCircle((int) this.centerX, (int) this.centerY,this.joystickRadius / 2, this.secondaryCircle); paramCanvas.drawLine((float) this.centerX, (float) this.centerY, (float) this.centerX, (float) (this.centerY - this.joystickRadius), this.verticalLine); paramCanvas.drawLine((float) (this.centerX - this.joystickRadius),(float) this.centerY,(float) (this.centerX + this.joystickRadius),(float) this.centerY, this.horizontalLine); paramCanvas.drawLine((float) this.centerX, (float) (this.centerY + this.joystickRadius), (float) this.centerX, (float) this.centerY, this.horizontalLine); paramCanvas.drawCircle(this.xPosition, this.yPosition,this.buttonRadius, this.button); } protected void onFinishInflate() { } protected void onMeasure(int paramInt1, int paramInt2) { int i = Math.min(measure(paramInt1), measure(paramInt2)); setMeasuredDimension(i, i); } protected void onSizeChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { super.onSizeChanged(paramInt1, paramInt2, paramInt3, paramInt4); this.xPosition = (getWidth() / 2); this.yPosition = (getWidth() / 2); int i = Math.min(paramInt1, paramInt2); this.buttonRadius = (int) (0.20D * (i / 2)); this.joystickRadius = (int) (0.75D * (i / 2)); } @Override public boolean onTouchEvent(MotionEvent paramMotionEvent) { //根據(jù)手觸碰的坐標決定紅色小圓的位置 this.xPosition = (int) paramMotionEvent.getX(); this.yPosition = (int) paramMotionEvent.getY(); double d = Math.sqrt((this.xPosition - this.centerX)* (this.xPosition - this.centerX)+ (this.yPosition - this.centerY)* (this.yPosition - this.centerY)); if (d > this.joystickRadius) { this.xPosition = (int) ((this.xPosition - this.centerX) * this.joystickRadius / d + this.centerX); this.yPosition = (int) ((this.yPosition - this.centerY) * this.joystickRadius / d + this.centerY); } invalidate();//再重新繪制 if (paramMotionEvent.getAction() == 1) { this.xPosition = (int) this.centerX; this.yPosition = (int) this.centerY; this.thread.interrupt(); if (this.onmywheelMoveListener != null)this.onmywheelMoveListener.onValueChanged(getAngle(), getPower()); } if ((this.onmywheelMoveListener != null)&& (paramMotionEvent.getAction() == 0)) { if ((this.thread != null) && (this.thread.isAlive()))this.thread.interrupt(); this.thread = new Thread(this); this.thread.start(); if (this.onmywheelMoveListener != null)//自定義接口處理觸摸事件this.onmywheelMoveListener.onValueChanged(getAngle(), getPower()); } return true; } @Override public void run() { while (true) { if (Thread.interrupted())return; post(new Runnable() {public void run() {// Log.e(tag, '運行在'+Thread.currentThread().getName()+'線程中'); if (MyWheel.this.onmywheelMoveListener != null) MyWheel.this.onmywheelMoveListener.onValueChanged(MyWheel.this.getAngle(),MyWheel.this.getPower());} }); try {Thread.sleep(this.loopInterval); } catch (InterruptedException localInterruptedException) { } } } public void setOnMyWheelMoveListener( OnMyWheelMoveListener paramOnJoystickMoveListener, long paramLong) { this.onmywheelMoveListener = paramOnJoystickMoveListener; this.loopInterval = paramLong; } public static abstract interface OnMyWheelMoveListener { public abstract void onValueChanged(int paramInt1, int paramInt2); } @SuppressLint('ClickableViewAccessibility') @Override public boolean onTouch(View v, MotionEvent event) { /*處理這個控件的觸摸事件*/ return true; }}

怎么用?下面我給出我的調(diào)用實例進行講解

首先在XML文件中應(yīng)用。

<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android' android:layout_width='match_parent' android:layout_height='match_parent' android:gravity='center' android:orientation='vertical' > <LinearLayout android:layout_width='wrap_content' android:layout_height='wrap_content' android:orientation='horizontal' > <Button android: android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='1' android:text='蹲下' /> <Button android: android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='1' android:text='站立' /> <Button android: android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='1' android:text='準備' /> <Button android: android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='1' android:text='坐下' /> <Button android: android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='1' android:text='零態(tài)' /> </LinearLayout> <com.sshhsun.socketudp.utils.MyWheel android: android:layout_width='wrap_content' android:layout_height='wrap_content' /> <TextView android: android:layout_width='wrap_content' android:layout_height='wrap_content' android:text='這是簡單控制界面' /> <LinearLayout android:layout_width='wrap_content' android:layout_height='wrap_content' android:orientation='vertical' > <SeekBar android: android:layout_width='match_parent' android:layout_height='wrap_content' android:minHeight='3dp' android:minWidth='260dp' android:progress='100' /> </LinearLayout></LinearLayout>

在一個Fragment中引用實例并處理相應(yīng)監(jiān)聽事件。

package com.sshhsun.socketudp.fragment;import android.content.Context;import android.os.Bundle;import android.os.Vibrator;import android.support.v4.app.Fragment;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView.FindListener;import android.widget.Button;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;import android.widget.Toast;import com.sshhsun.socketudp.R;import com.sshhsun.socketudp.activity.constant.Constant;import com.sshhsun.socketudp.utils.MyWheel;import com.sshhsun.socketudp.utils.MyWheel.OnMyWheelMoveListener;import com.sshhsun.socketudp.utils.UDPUtil;public class SimpleFragment extends Fragment implements View.OnClickListener { private MyWheel mtwheel; private TextView notice; private TextView show; private String direction = 'none'; private SeekBar seekbar; private static final String tag = 'SimpleFragment'; Vibrator vibator; private Context context = getActivity(); private boolean isturn = false; private Button stand; private Button sit; private Button standinit; private Button rest; private Button standzero; private UDPUtil udpUtil; private boolean issend = false; private boolean isstop = true; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return initView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(); initListener(); } public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_simple, null); //我的方向盤控件mtwheel mtwheel = (MyWheel) view.findViewById(R.id.mywheel); //控件下面的提示信息notice,其他控件大家可以忽略. notice = (TextView) view.findViewById(R.id.notice); seekbar = (SeekBar) view.findViewById(R.id.turns); seekbar.setProgress(50); stand = (Button) view.findViewById(R.id.simple_stand); sit = (Button) view.findViewById(R.id.simple_sit); standinit = (Button) view.findViewById(R.id.simple_standinit); rest = (Button) view.findViewById(R.id.simple_rest); standzero = (Button) view.findViewById(R.id.simple_standzero); return view; } public void initListener() { sit.setOnClickListener(this); standinit.setOnClickListener(this); rest.setOnClickListener(this); standzero.setOnClickListener(this); stand.setOnClickListener(this); //下面的監(jiān)聽器代碼最為重要!!!!!!!! mtwheel.setOnMyWheelMoveListener(new OnMyWheelMoveListener() { @Override // paramInt1:角度 // paramInt2:距離 根據(jù)這兩個參數(shù)可以算出方向盤的方位 public void onValueChanged(int paramInt1, int paramInt2) {boolean isdistance = false;if (paramInt2 >= 50) { isdistance = true; int temp = Math.abs(paramInt1); if (paramInt1 >= 0) { if (temp > 50 && temp < 120) { direction = 'right'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else if (temp < 40) { direction = 'forward'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else if (temp > 140) { direction = 'back'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else { direction = '指向不明確'; issend = false; } } else { if (temp > 50 && temp < 120) { direction = 'left'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else if (temp < 40) { direction = 'forward'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else if (temp > 140) { direction = 'back'; if (!issend) {udpUtil.UdpSend(direction, Constant.port);issend = true;isstop = false; } } else { direction = '指向不明確'; issend = false; } }} else { isdistance = false; direction = 'stop'; issend = false;}notice.setText(' getAngle:' + paramInt1 + 'n' + ' getPower:' + paramInt2 + 'n' + 'direction:' + direction);if (direction.equals('stop') && (!isstop)) { udpUtil.UdpSend(direction, Constant.port); isstop = true;} } }, 100L); seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) {seekbar.setProgress(50);isturn = false;String command = 'stop';udpUtil.UdpSend(command, Constant.port); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {int cucrrent = seekbar.getProgress();String command = 'hello';if (cucrrent < 20) { Toast.makeText(getActivity(), 'onProgressChanged' + '左轉(zhuǎn)', 0) .show(); if (!isturn) { Log.e(tag, 'onProgressChanged' + '左轉(zhuǎn)'); command = 'turnleft'; udpUtil.UdpSend(command, Constant.port); vibator.vibrate(100); isturn = true; }} else if (cucrrent > 80) { Toast.makeText(getActivity(), 'onProgressChanged' + '右轉(zhuǎn)', 0) .show(); if (!isturn) { Log.e(tag, 'onProgressChanged' + '右轉(zhuǎn)'); command = 'turnright'; udpUtil.UdpSend(command, Constant.port); vibator.vibrate(100); isturn = true; }} } }); } public void initData() { udpUtil = new UDPUtil(Constant.Address); vibator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE); Thread.currentThread().setName(tag); } public void processClick(View v) { String command = 'hello'; switch (v.getId()) { case R.id.simple_rest: command = 'rest'; break; case R.id.simple_sit: command = 'sit'; break; case R.id.simple_stand: command = 'stand'; break; case R.id.simple_standinit: command = 'standinit'; break; case R.id.simple_standzero: command = 'standzero'; break; default: break; } udpUtil.UdpSend(command, Constant.port); } @Override public void onClick(View v) { processClick(v); } @Override public void onDestroy() { super.onDestroy(); vibator.cancel(); } // @Override // public boolean onTouch(View v, MotionEvent event) { // if (v.getId() == R.id.turns) { // String notice = ''; // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // notice = 'ACTION_DOWN'+event.getX(); // int process=(int) Math.floor(event.getX()+0.5); // seekbar.setProgress(process); // break; // case MotionEvent.ACTION_UP: // notice = 'ACTION_UP'; // break; // case MotionEvent.ACTION_CANCEL: // notice = 'ACTION_CANCEL'; // break; // default: // break; // } // if (!TextUtils.isEmpty(notice)) { // Toast.makeText(getActivity(), notice, 0).show(); // } // } // return true; // }}

聲明一下:

1.上面的控件代碼(第一部分代碼)可以實際使用 2.第二部分代碼演示了控件的使用與處理 3.關(guān)于控件的實現(xiàn)原理和思想在代碼與注釋中已經(jīng)詳細標記

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Android
相關(guān)文章:
主站蜘蛛池模板: 板框压滤机-隔膜压滤机配件生产厂家-陕西华星佳洋装备制造有限公司 | 广州迈驰新GMP兽药包装机首页_药品包装机_中药散剂包装机 | 番茄畅听邀请码怎么输入 - Dianw8.com| 铝镁锰板_铝镁锰合金板_铝镁锰板厂家_铝镁锰金属屋面板_安徽建科 | 游动电流仪-流通式浊度分析仪-杰普仪器(上海)有限公司 | 冷水机-工业冷水机-冷水机组-欧科隆品牌保障 | 高低温试验箱-模拟高低温试验箱订制-北京普桑达仪器科技有限公司【官网】 | 无菌实验室规划装修设计-一体化实验室承包-北京洁净净化工程建设施工-北京航天科恩实验室装备工程技术有限公司 | 心肺复苏模拟人|医学模型|急救护理模型|医学教学模型上海康人医学仪器设备有限公司 | 【连江县榕彩涂料有限公司】官方网站 | 耳模扫描仪-定制耳机设计软件-DLP打印机-asiga打印机-fitshape「飞特西普」 | 艾默生变频器,艾默生ct,变频器,ct驱动器,广州艾默生变频器,供水专用变频器,风机变频器,电梯变频器,艾默生变频器代理-广州市盟雄贸易有限公司官方网站-艾默生变频器应用解决方案服务商 | 冲击式破碎机-冲击式制砂机-移动碎石机厂家_青州市富康机械有限公司 | 北京网站建设首页,做网站选【优站网】,专注北京网站建设,北京网站推广,天津网站建设,天津网站推广,小程序,手机APP的开发。 | 半自动预灌装机,卡式瓶灌装机,注射器灌装机,给药器灌装机,大输液灌装机,西林瓶灌装机-长沙一星制药机械有限公司 | 单级/双级旋片式真空泵厂家,2xz旋片真空泵-浙江台州求精真空泵有限公司 | 电采暖锅炉_超低温空气源热泵_空气源热水器-鑫鲁禹电锅炉空气能热泵厂家 | 广州展览制作工厂—[优简]直营展台制作工厂_展会搭建资质齐全 | 防爆电机-高压防爆电机-ybx4电动机厂家-河南省南洋防爆电机有限公司 | 存包柜厂家_电子存包柜_超市存包柜_超市电子存包柜_自动存包柜-洛阳中星 | 上海租奔驰_上海租商务车_上海租车网-矢昂汽车服务公司 | 2025福建平潭岛旅游攻略|蓝眼泪,景点,住宿攻略-趣平潭网 | 我车网|我关心的汽车资讯_汽车图片_汽车生活! | 压砖机、液压制砖机、静压砖机、环保砖机生产厂家—杜甫机械 | 脱硝喷枪-氨水喷枪-尿素喷枪-河北思凯淋环保科技有限公司 | 首页-瓜尔胶系列-化工单体系列-油田压裂助剂-瓜尔胶厂家-山东广浦生物科技有限公司 | 球磨机 选矿球磨机 棒磨机 浮选机 分级机 选矿设备厂家 | 广州食堂承包_广州团餐配送_广州堂食餐饮服务公司 - 旺记餐饮 | 轻型地埋电缆故障测试仪,频响法绕组变形测试仪,静荷式卧式拉力试验机-扬州苏电 | 盐城网络公司_盐城网站优化_盐城网站建设_盐城市启晨网络科技有限公司 | 铝合金线槽_铝型材加工_空调挡水板厂家-江阴炜福金属制品有限公司 | 丹尼克尔拧紧枪_自动送钉机_智能电批_柔性振动盘_螺丝供料器品牌 | 衬氟止回阀_衬氟闸阀_衬氟三通球阀_衬四氟阀门_衬氟阀门厂-浙江利尔多阀门有限公司 | 广州监控安装公司_远程监控_安防弱电工程_无线wifi覆盖_泉威安防科技 | 长沙广告公司_制作,长沙喷绘_发光字_招牌制作_长沙泓润广告官网 长城人品牌官网 | 品牌策划-品牌设计-济南之式传媒广告有限公司官网-提供品牌整合丨影视创意丨公关活动丨数字营销丨自媒体运营丨数字营销 | 奥因-光触媒除甲醛公司-除甲醛加盟公司十大品牌 | 膏剂灌装旋盖机-眼药水灌装生产线-西林瓶粉剂分装机-南通博琅机械科技 | 潍坊大集网-潍坊信息港-潍坊信息网| 布袋除尘器-单机除尘器-脉冲除尘器-泊头市兴天环保设备有限公司 布袋除尘器|除尘器设备|除尘布袋|除尘设备_诺和环保设备 | 南昌旅行社_南昌国际旅行社_南昌国旅在线|