Android触屏测试实例代码

时间:2021-05-20

本文实例详细描述了Android触屏测试代码,可实现对触屏的点击、移动、离开等事件的处理,对于Android初学者有很好的借鉴价值。

具体功能代码如下:

package com.test;import android.app.Activity;import android.os.Bundle;import android.util.DisplayMetrics;import android.util.Log;import android.view.MotionEvent;import android.view.View;import android.widget.AbsoluteLayout;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;public class TouchActivity extends Activity { private ImageView mImageView01; private int intWidth, intHeight, intDefaultX, intDefaultY; private float mX, mY; private int intScreenX, intScreenY; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); intScreenX = dm.widthPixels; intScreenY = dm.heightPixels; intWidth = 100; intHeight = 100; mImageView01 =(ImageView) findViewById(R.id.myImageView1); mImageView01.setImageResource(R.drawable.baby); RestoreButton(); mImageView01.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { RestoreButton(); } }); } public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); try { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: picMove(x, y); break; case MotionEvent.ACTION_MOVE: picMove(x, y); break; case MotionEvent.ACTION_UP: picMove(x, y); break; } }catch(Exception e) { e.printStackTrace(); } return true; } private void picMove(float x, float y) { mX=x-(intWidth/2); mY=y-(intHeight/2); if((mX+intWidth)>intScreenX) { mX = intScreenX-intWidth; } else if(mX<0) { mX = 0; } else if ((mY+intHeight)>intScreenY) { mY=intScreenY-intHeight; } else if (mY<0) { mY = 0; } Log.i("jay", Float.toString(mX)+","+Float.toString(mY)); mImageView01.setLayoutParams ( new AbsoluteLayout.LayoutParams (intWidth,intHeight,(int) mX,(int)mY) ); } public void RestoreButton() { intDefaultX = ((intScreenX-intWidth)/2); intDefaultY = ((intScreenY-intHeight)/2); mMakeTextToast ( "("+ Integer.toString(intDefaultX)+ ","+ Integer.toString(intDefaultY)+")",true ); mImageView01.setLayoutParams ( new AbsoluteLayout.LayoutParams (intWidth,intHeight,intDefaultX,intDefaultY) ); } public void mMakeTextToast(String str, boolean isLong) { if(isLong==true) { Toast.makeText(TouchActivity.this, str, Toast.LENGTH_LONG).show(); } else { Toast.makeText(TouchActivity.this, str, Toast.LENGTH_SHORT).show(); } }}

读者还可以在该实例的基础上完善各种事件的响应处理函数,使其功能更加丰富。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章