android确定屏幕的中心位置?

我想每次加载都能获取屏幕的中心位置,注意收集屏幕不一样的处理哦?

6个回答

int[] iv_locations = new int[2];
iv.getLocationInWindow(iv_locations); //获取在当前窗口内的绝对坐标
iv.getLocationOnScreen(iv_locations);//获取在整个屏幕内的绝对坐标
int x = iv_locations[0];//横坐标
int y = iv_locations[1];//纵坐标

int cx = (width - bit_width) / 2;
int cy = (height - stateHeight - bit_height) / 2;
Bitmap bi = BitmapFactory.decodeResource(m_context.getResources(),
R.drawable.icon_map_center_point, options);

canvas.drawBitmap(bi, cx, cy, m_paint);
}

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
int screenHeigh = dm.heightPixels;
int px = screenWidth / 2;
int py = screenHeight/2;

你获取设备屏幕的宽高,然后除以二不就能得到当前屏幕的中心位置了吗

赞同楼上Trent1985 的代码,没有错的,我这样写过

赞楼上的方法,其次你可以写一个布局充满屏幕,然后计算布局的宽高/2即可

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Android:如何获得屏幕尺寸?
我创建了一些自定义元素,我想要通过程序把它们放在屏幕的右上角(像素n是距离顶部边距,像素m是距离右边边距),因此我需要得到屏幕的宽度和高度,然后确定放置的位置: int px = screenWidth - m; int py = screenWidth - n; 有人知道在Activity组件中如何得到屏幕的宽度和高度么? 谢谢。
关于Android里面fill_parent跟wrap_content 到底该怎么用
网上搜的大概意思就是fill_parent 将控件填充整个屏幕 ,wrap_content是根据内容确定大小。 但是我用了 达不到我想要的效果。代码如下。 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="注册"/> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow android:gravity="left" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="账户:" /> <EditText android:id="@+id/userName" android:layout_width="fill_parent" android:layout_height="35px"/> </TableRow> <TableRow android:gravity="left"> <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="密码:"/> <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="35px" android:inputType="numberPassword"/> </TableRow> <TableRow android:gravity="left"> <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="确认:" /> <EditText android:id="@+id/agin" android:layout_width="fill_parent" android:layout_height="35px" android:inputType="numberPassword"/> </TableRow> <TableRow android:gravity="left"> <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="省份:"/> <EditText android:id="@+id/sheng" android:layout_width="fill_parent" android:layout_height="35px" /> <Button android:layout_width="fill_parent" android:layout_height="40px" android:id="@+id/shengsubmit" android:text="选择"/> </TableRow> <TableRow android:gravity="left"> <TextView android:layout_width="fill_parent" android:layout_height="35px" android:text="市/州:"/> <EditText android:id="@+id/shi" android:layout_width="fill_parent" android:layout_height="35px" /> <Button android:layout_width="fill_parent" android:layout_height="40px" android:id="@+id/shisubmit" android:text="选择"/> </TableRow> <TableRow android:gravity="center"> <Button android:layout_width="fill_parent" android:layout_height="40px" android:id="@+id/registSubmit" android:text="注册"/> </TableRow> </TableLayout> </LinearLayout> 图一是实际效果。图二是我想要的。但是代码编写的好像跟我想的不一样。所以就大神帮我仔细解释下到底怎么用。另外,听说fill_parent说是继承父控件的大小。希望能给我解释的清楚些![![图片说明](https://img-ask.csdn.net/upload/201509/14/1442201762_439286.png)图片说明](https://img-ask.csdn.net/upload/201509/14/1442201754_951920.png)
Android 悬浮窗获取点击拖拽事件
之前参照网上例子写过一个demo,实现在Activity中点击最小化按钮,将该Activity finish,并启动servie生成一个悬浮按钮,可点击也可拖拽; 最近工作需要也做一个相似的悬浮窗,悬浮按钮生成了,App被Home也能存在,不会 消失,但该悬浮按钮却没法捕获点击和拖拽事件。 这两个代码几乎一摸一样,请大神们帮忙看下是哪里出的问题,谢谢! 代码如下: package com.example.menqi.myapplication; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; public class MyService extends Service { private WindowManager mWindowManager; private WindowManager.LayoutParams mLayoutParams; /** * float的布局view */ private View mFloatView; private ViewGroup glSurfaceView; private int mFloatWinWidth,mFloatWinHeight;//悬浮窗的宽高 //private int mFloatWinMarginTop,mFloatWinMarginRight; public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return null; } @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { createWindowManager(); createFloatView(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); removeFloatView(); } private void createWindowManager() { // 取得系统窗体 mWindowManager= (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE); //计算得出悬浮窗口的宽高 DisplayMetrics metric =new DisplayMetrics(); mWindowManager.getDefaultDisplay().getMetrics(metric); int screenWidth = metric.widthPixels; mFloatWinWidth = screenWidth *1/3; mFloatWinHeight=mFloatWinWidth*4/3; //mFloatWinMarginTop= (int)this.getResources().getDimension(R.dimen.rkcloud_av_floatwin_margintop); //mFloatWinMarginRight= (int)this.getResources().getDimension(R.dimen.rkcloud_av_floatwin_marginright); // 窗体的布局样式 // 获取LayoutParams对象 mLayoutParams=new WindowManager.LayoutParams(); // 确定爱悬浮窗类型,表示在所有应用程序之上,但在状态栏之下 //TODO? 在android2.3以上可以使用TYPE_TOAST规避权限问题 mLayoutParams.type= WindowManager.LayoutParams.TYPE_TOAST;//TYPE_PHONE mLayoutParams.format= PixelFormat.RGBA_8888; mLayoutParams.flags= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; // 悬浮窗的对齐方式 mLayoutParams.gravity= Gravity.LEFT| Gravity.TOP; // 悬浮窗的位置 mLayoutParams.x=70; mLayoutParams.y=210; mLayoutParams.width=mFloatWinWidth; mLayoutParams.height=mFloatWinHeight; } //开始触控的坐标,移动时的坐标(相对于屏幕左上角的坐标) private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY; //开始时的坐标和结束时的坐标(相对于自身控件的坐标) private int mStartX, mStartY, mStopX, mStopY; //判断悬浮窗口是否移动,这里做个标记,防止移动后松手触发了点击事件 private boolean isMove; /** * 创建悬浮窗 */ private void createFloatView() { LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); mFloatView= inflater.inflate(R.layout.floatlayout, null); glSurfaceView= (ViewGroup)mFloatView.findViewById(R.id.VOIPFloatView); //glSurfaceView.setPreserveEGLContextOnPause(true); glSurfaceView.setKeepScreenOn(true); mWindowManager.addView(mFloatView,mLayoutParams); mFloatView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v,MotionEvent event) { int action = event.getAction(); /*if(MotionEvent.ACTION_DOWN == action) { mStartX=mLastX= (int) event.getRawX(); mStartY=mLastY= (int) event.getRawY(); }else if(MotionEvent.ACTION_UP == action) { int dx = (int) event.getRawX() -mStartX; int dy = (int) event.getRawY() -mStartY; if(Math.abs(dx) >5|| Math.abs(dy) >5) { return true; } }else if(MotionEvent.ACTION_MOVE == action) { int dx = (int) event.getRawX() -mLastX; int dy = (int) event.getRawY() -mLastY; mLayoutParams.x=mLayoutParams.x- dx; mLayoutParams.y=mLayoutParams.y+ dy; mWindowManager.updateViewLayout(mFloatView,mLayoutParams); mLastX= (int) event.getRawX(); mLastY= (int) event.getRawY(); } return false;*/ switch (action) { case MotionEvent.ACTION_DOWN: isMove = false; mTouchStartX = (int) event.getRawX(); mTouchStartY = (int) event.getRawY(); mStartX = (int) event.getX(); mStartY = (int) event.getY(); break; case MotionEvent.ACTION_MOVE: mTouchCurrentX = (int) event.getRawX(); mTouchCurrentY = (int) event.getRawY(); mLayoutParams.x += mTouchCurrentX - mTouchStartX; mLayoutParams.y += mTouchCurrentY - mTouchStartY; mWindowManager.updateViewLayout(mFloatView, mLayoutParams); mTouchStartX = mTouchCurrentX; mTouchStartY = mTouchCurrentY; break; case MotionEvent.ACTION_UP: mStopX = (int) event.getX(); mStopY = (int) event.getY(); if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) { isMove = true; } break; } //如果是移动事件不触发OnClick事件,防止移动的时候一放手形成点击事件 return isMove; } }); mFloatView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ToVOIPActivity(); MyService.this.stopSelf(); } }); /*VideoRendererGui.setView(glSurfaceView, new Runnable() { @Override public void run() { if(WebRtcHelperEx.getInstance().isWebRtcChanelAlive()) { WebRtcHelperEx.getInstance().updateVideoUI(WebRtcHelperEx.latestLocalVideoSize,WebRtcHelperEx.latestRemoteVideoSize); } } }); if(WebRtcHelperEx.getInstance().isWebRtcChanelAlive()) { LogEx.d(TAG,"createFloatView: webrtc instance is alive and we will call resetRenders"); WebRtcHelperEx.getInstance().resetRenders(); WebRtcHelperEx.getInstance().updateVideoUI(WebRtcHelperEx.VIDEOSIZE_SMALL,WebRtcHelperEx.VIDEOSIZE_BIG); }*/ } private void removeFloatView() { if(mFloatView != null && mWindowManager != null) { mWindowManager.removeView(mFloatView); } } /** * 单击后回到@WebRTCActivity以切换为大尺寸页面 */ private void ToVOIPActivity() { //TODO跳转到Activity Intent intentToActivity = new Intent(this, Main2Activity.class);//WebPhoneIncomingCallActivity来电页面 intentToActivity.setFlags(FLAG_ACTIVITY_NEW_TASK); startActivity(intentToActivity); } } layout <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/VOIPFloatView" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/avcallfloat" android:scaleType="centerInside" /> </FrameLayout> </RelativeLayout> </RelativeLayout>
android gridview一排显示几个如何自适应屏幕宽度?
![图片说明](https://img-ask.csdn.net/upload/201612/15/1481766171_239395.png) 目前做的项目,商品选择属性 我用listview嵌套gridview实现的,但是有个问题,美工的设计要求是gridview的每排显示的个数是不确定的,比如说文字长的话一排显示3个,字数少的话,一排显示4-5个. 请问大神如何实现,或者不用我这种嵌套方式,用什么比较好?求解答~~~谢谢
Android中surfaceView画直线断断续续
使用surfaceView做了一个画画板的练习,可是画出来的线断断续续,是为什么? 下面是mainactivity package com.wxh.mywall; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Bundle; import android.view.Menu; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private SurfaceView mSurfaceView = null; private SurfaceHolder mSurfaceHolder = null; private Button cleanButton = null; private Button colorButton = null; private float oldX = 0f; private float oldY = 0f; private boolean canDraw = false; private Paint mPaint = null; //用来记录当前是哪一种颜色 private int whichColor = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSurfaceView = (SurfaceView)this.findViewById(R.id.surfaceview); mSurfaceHolder = mSurfaceView.getHolder(); mPaint = new Paint(); //画笔的颜色 mPaint.setColor(Color.RED); //画笔的粗细 mPaint.setStrokeWidth(2.0f); cleanButton = (Button)this.findViewById(R.id.flushbutton); //按钮监听 cleanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //锁定整个SurfaceView Canvas mCanvas = mSurfaceHolder.lockCanvas(); mCanvas.drawColor(Color.BLACK); //绘制完成,提交修改 mSurfaceHolder.unlockCanvasAndPost(mCanvas); //重新锁一次 mSurfaceHolder.lockCanvas(new Rect(0, 0, 0, 0)); mSurfaceHolder.unlockCanvasAndPost(mCanvas); } }); colorButton = (Button)this.findViewById(R.id.colorbutton); //按钮监听 colorButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Dialog mDialog = new AlertDialog.Builder(MainActivity.this) .setTitle("颜色设置") .setSingleChoiceItems(new String[]{"红色","绿色","蓝色"}, whichColor, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub switch(which) { case 0: { //画笔的颜色 mPaint.setColor(Color.RED); whichColor = 0; break; } case 1: { //画笔的颜色 mPaint.setColor(Color.GREEN); whichColor = 1; break; } case 2: { //画笔的颜色106 mPaint.setColor(Color.BLUE); whichColor = 2; break; } } } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }) .create(); mDialog.show(); } }); } @Override public boolean onTouchEvent(MotionEvent event) { //获取x坐标 float x = event.getX(); //获取y坐标(不知道为什么要减去两个偏移值才对得准屏幕) float y = event.getY()-100; //第一次进来先不管 if(canDraw) { //获取触屏事件 switch(event.getAction()) { //如果是拖动事件 case MotionEvent.ACTION_MOVE: { //锁定整个SurfaceView Canvas mCanvas = mSurfaceHolder.lockCanvas(); mCanvas.drawLine(x, y, oldX, oldY, mPaint); mSurfaceHolder.unlockCanvasAndPost(mCanvas); //重新锁一次 mSurfaceHolder.lockCanvas(new Rect(0, 0, 0, 0)); mSurfaceHolder.unlockCanvasAndPost(mCanvas); break; } } } //保存目前的x坐标值 oldX = x; //保存目前的y坐标值 oldY = y; canDraw = true; return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } ``` ```
刚学Android,一个AlertDialog的问题请教各位大大~~
想达到的效果是:按了一个按钮,弹出的选择框会显示两个选项----“手动输入”和“摄像头输入”,当我选中其中一个后,按“确认”按钮,屏幕下方会短暂显示一行“选择的输入方式:XX输入”,XX是我选中的方式。 目前的问题是:setSingleChoiceItems里面onClick方法不会写。 ![图片说明](https://img-ask.csdn.net/upload/201601/27/1453899192_126013.png)
Android 继承BridgeWebView 写个自定义的webview。部分手机加载高度为0
public class AdWebView extends com.github.lzyzsd.jsbridge.BridgeWebView { private Context mContext; private MoonthimpModel moonthimpModel; private boolean messageHeight; private String mTitle; private PregressChange pregressChange; public AdWebView(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AdWebView); messageHeight = a.getBoolean( R.styleable.AdWebView_messageHeight, false); } public void setPregressChange(PregressChange pregressChange) { this.pregressChange = pregressChange; } public AdWebView(Context context) { super(context); this.mContext = context; } Mobile mobile = new Mobile(); public void initWebView(String url) { WebSettings webSettings = getSettings(); //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript webSettings.setJavaScriptEnabled(true); //设置自适应屏幕,两者合用 webSettings.setDomStorageEnabled(true); // 解决Android 5.0上Webview默认不允许加载Http与Https混合内容 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //两者都可以 webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } //设置自适应屏幕,两者合用 webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小 webSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小 webSettings.setAllowFileAccess(true); //设置可以访问文件 webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true);//支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 addJavascriptInterface(this, "Android_kks"); if (messageHeight) { addJavascriptInterface(mobile, "mobile"); } if (Build.VERSION.SDK_INT >= 19) { getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); } //设置不用系统浏览器打开,直接显示在当前Webview setWebViewClient(new BridgeWebViewClient(this) { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); LogUtils.e("onPageFinished"); if (messageHeight) { mobile.onGetWebContentHeight(); } } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // super.onReceivedSslError(view, handler, error); 父类的默认处理方式,内部是handler.cancel(),必须去除 handler.proceed();// 接受所有网站的证书 // handleMessage(Message msg);// 进行其他处理 } }); setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (pregressChange != null) { if (newProgress == 100) { //加载完毕进度条消失 pregressChange.onComplete(); } else { //更新进度 pregressChange.onProgress(newProgress); } } super.onProgressChanged(view, newProgress); } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (title != null && pregressChange != null) { // pregressChange.onTitle(title); } } }); loadUrl(url); // loadUrl("https://h5.ruiccm.com/testls/190627/index.html"); // loadUrl("file:///android_asset/demo1.html"); String localVersion = ""; try { PackageInfo packageInfo = KeKeShiApp.getApp() .getPackageManager() .getPackageInfo(KeKeShiApp.getApp().getPackageName(), 0); localVersion = packageInfo.versionName; LogUtils.d("TAG", "本软件的版本号。。" + localVersion); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } AdUserInfoBean src = new AdUserInfoBean(); src.setDevice_uuid(PushAgent.getInstance(mContext).getRegistrationId()); if (AppSharedPrefs.getUserInfo() != null && AppSharedPrefs.getUserInfo().getUserinfo() != null && AppSharedPrefs.getUserInfo().getUserinfo().getTel() != null) { UserBean.UserInfo userinfo = AppSharedPrefs.getUserInfo().getUserinfo(); src.setPhoneNum(userinfo.getTel()); src.setBabybirthday(userinfo.getBabybirthday()); src.setBabyname(userinfo.getBabyname()); src.setBabysex(userinfo.getBabysex()); src.setIsvip((AppSharedPrefs.getUserInfo().getIsvip() ? 1 : 0) + ""); src.setMoonage(userinfo.getMoonage()); src.setRelative(userinfo.getRelative()); src.setUser_uuid(userinfo.getUuid()); } src.setDeviceid(PushAgent.getInstance(mContext).getRegistrationId()); src.setVersion(localVersion); src.setPhone_type("Android"); src.setPhone_version(SystemUtil.getSystemModel() + "," + SystemUtil.getSystemVersion()); //有方法名的都需要注册Handler后使用 registerHandler("userInfo", new BridgeHandler() { @Override public void handler(String data, CallBackFunction function) { Log.i("liuw", "html返回数据为:" + data); function.onCallBack("Native已经接收到数据:" + data + ",请确认!"); } }); //应用启动后初始化数据调用,js处理方法connectWebViewJavascriptBridge(function(bridge) callHandler("userInfo", new Gson().toJson(src), new CallBackFunction() { @Override public void onCallBack(String data) { Log.e("callbace", "successs"); } }); } public String getmTitle() { return mTitle; } private class Mobile { @JavascriptInterface public void onGetWebContentHeight() { post(new Runnable() { @Override public void run() { measure(0, 0); int measuredHeight = getMeasuredHeight(); LogUtils.d("measuredHeight", measuredHeight + ""); SharedPreferences kekeshi = mContext.getSharedPreferences("kekeshi", MODE_PRIVATE); if (measuredHeight != 0) { kekeshi.edit().putInt("measuredHeight", measuredHeight).commit(); } LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) getLayoutParams(); params.height = measuredHeight; if (measuredHeight == 0) { int measuredHeight1 = kekeshi.getInt("measuredHeight", 4000); params.height = measuredHeight1; } params.weight = LinearLayout.LayoutParams.MATCH_PARENT; setLayoutParams(params); } }); } } public void close() { stopLoading(); clearHistory(); removeAllViews(); destroy(); } public void resume() { // resumeTimers(); // onResume(); } public void pause() { // onPause(); // pauseTimers(); } public void load(String url) { initWebView(url); } public interface PregressChange { void onComplete(); void onProgress(int progress); void onTitle(String title); } ``` ```
所做Android打砖块代码其中 出错 求教
下面是代码 可其中出现了一个错误(做了标记),不知道怎么解决,可否有高手帮我看看,能不能稍作修改一下,做成正确的。 就是这句错了 myview = new BallView(this); package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由xxx制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; setTitle("宽"+screenWidth+" 高"+screenHeight); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); `myview = new BallView(this);` //错误在这里 setContentView(myview); } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MENU: myview.resetGame(); break; case KeyEvent.KEYCODE_DPAD_CENTER: myview.ball_isRun = !myview.ball_isRun; break; case KeyEvent.KEYCODE_DPAD_LEFT: if(myview.ball_isRun){ if(myview.board_left<=myview.board_x_move) { myview.board_left=0; myview.board_right=myview.board_length; }else{ myview.board_left-=myview.board_x_move; myview.board_right-=myview.board_x_move;} } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if(myview.ball_isRun){ if(screenWidth-myview.board_right<=myview.board_x_move ) { myview.board_left=screenWidth-myview.board_length; myview.board_right=screenWidth; }else{ myview.board_left+=myview.board_x_move; myview.board_right+=myview.board_x_move; } } break; case KeyEvent.KEYCODE_DPAD_UP: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top) { myview.board_alterable_top-=myview.boardYadd; myview.board_alterable_bottom-=myview.boardYadd; } } break; case KeyEvent.KEYCODE_DPAD_DOWN: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top-myview.boardYadd ) { myview.board_alterable_top=myview.board_default_top; myview.board_alterable_bottom=myview.board_alterable_top+myview.board_thickness; } } break; case KeyEvent.KEYCODE_BACK: dazhuankuaiActivity.this.finish(); break; }//end switch return false; } //按键弹起事件 } ); } } package sen.tan; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = dazhuankuaiActivity.screenWidth;//320 screen_height = dazhuankuaiActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.YELLOW); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.BLUE); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// canvas.drawPoint(board_left+ball2_r, screen_height-ball2_r, mPaint2);//绘制左轮轮心 canvas.drawPoint(board_right-ball2_r, screen_height-ball2_r, mPaint2);//绘制右轮轮心 }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } 下个界面的代码是 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } }
Android 怎么将主程序添加到欢迎界面里面
我做好了一个欢迎界面,并且做了下按钮触发,里面什么都还没有,我这边有一个游戏主程序,应该怎么样才能合理的添加进去呢? 添加的结果就是 点击这个按钮 就进入这个主程序。下面是代码 这个是我的欢迎界面的代码 package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由xxx制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { } }); 下面是我找到的主程序 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } package ab.cc; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = BaomingActivity.screenWidth;//320 screen_height = BaomingActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.MAGENTA); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.BLACK); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.RED); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } 能否回答的详细一点,学的时间短,求帮忙
Android打砖块代码 其中系统说格式错误 求帮助
我这边有一个打砖块代码,我将它移植到我的按钮事件触发里 提示我格式错误 下面前两个是打砖块代码 ,后两个是转到我的里面之后的, 标注了,请帮忙。 package ab.cc; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class BaomingActivity extends Activity { BallView myView; static int screenWidth; static int screenHeight; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* 定义DisplayMetrics对象 */ DisplayMetrics dm = new DisplayMetrics(); /* 取得窗口属性 */ getWindowManager().getDefaultDisplay().getMetrics(dm); /* 窗口的宽度 */ screenWidth = dm.widthPixels; /* 窗口的高度 */ screenHeight = dm.heightPixels; // setTitle("宽"+screenWidth+" 高"+screenHeight); /* 设置为无标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设置为全屏模式 */ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myView = new BallView(this); //设置显示GameSurfaceView视图 setContentView(myView); }//end of onCreate() //触笔事件 public boolean onTouchEvent(MotionEvent event) { return true; } //按键按下事件 public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { //菜单按键-设为初始菜单 case KeyEvent.KEYCODE_MENU: myView.resetGame(); //重新开始 break; //中间按键 case KeyEvent.KEYCODE_DPAD_CENTER: myView.ball_isRun = !myView.ball_isRun;//开始//暂停 break; //左方向键 case KeyEvent.KEYCODE_DPAD_LEFT: if(myView.ball_isRun){ if(myView.board_left<=myView.board_x_move) { myView.board_left=0; myView.board_right=myView.board_length; }else{ myView.board_left-=myView.board_x_move; myView.board_right-=myView.board_x_move;} } break; //右方向键 case KeyEvent.KEYCODE_DPAD_RIGHT: if(myView.ball_isRun){ if(screenWidth-myView.board_right<=myView.board_x_move ) { myView.board_left=screenWidth-myView.board_length; myView.board_right=screenWidth; }else{ myView.board_left+=myView.board_x_move; myView.board_right+=myView.board_x_move; } } break; //上方向键 case KeyEvent.KEYCODE_DPAD_UP: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top) { myView.board_alterable_top-=myView.boardYadd; myView.board_alterable_bottom-=myView.boardYadd; } } break; //下方向键 case KeyEvent.KEYCODE_DPAD_DOWN: if(myView.ball_isRun){ if( myView.board_alterable_top==myView.board_default_top-myView.boardYadd ) { myView.board_alterable_top=myView.board_default_top; myView.board_alterable_bottom=myView.board_alterable_top+myView.board_thickness; } } break; //返回键 case KeyEvent.KEYCODE_BACK: this.finish(); break; }//end switch return false; } //按键弹起事件 public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } package ab.cc; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Shader; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; public class BallView extends SurfaceView implements SurfaceHolder.Callback, Runnable { //线程延时控制 final int ball_sleep=1;//毫秒,延时越大,球速越慢 final int ball_r= 8;//小球半径 final float ball2_r= 8;//底下滚珠小球半径 final int ballXorYadd = 4;//小球的基本位移。测试可行值:2,4 //获取屏幕宽度和高度 int screen_width;//320; int screen_height;//480; //砖的属性 int brick_width;//每块砖宽 int brick_height;//每块砖高 boolean brick_exist[];//砖是否存在 int k ;// 列//到for循环里才初始化 int j ;// 行 int brick_left = brick_width*(k-1);//到判断语句才初始化 int brick_right = brick_width*k; int brick_top = brick_height*j; int brick_bottom = brick_height*(j+1); //挡板的属性 int board_length;//挡板长度:80比较合适,可以随意修改,但别超过screen_width final int boardYadd = 16;//按上下键时挡板y方向位移量。经验证4、8、16可以,12不行 final int board_x_move = 30;//挡板x方向位移量:可以随意自定义 int board_left;//挡板左侧(可变) int board_right;//挡板右侧(可变) int board_thickness;//挡板厚度 int board_default_top;//即435,挡板的top面初始位置 int board_alterable_top;//挡板上侧(可变) int board_alterable_bottom;//挡板下侧(可变) int ball_default_x;//球的初始x坐标 int ball_default_y;//球的初始y坐标 //球的即时坐标(可变): int ball_x;//球心横坐标 int ball_y;//球心纵坐标 //球的前一步的y坐标 int ball_previous_y; int ball_x_speed;//球的横向偏移量//可变 int ball_y_speed;//球的纵向偏移量//可变 boolean ball_isRun;//球是否在动 // 控制循环 boolean mbLoop; // 定义SurfaceHolder对象 SurfaceHolder mSurfaceHolder = null; //获得分数 int score; /* 唤醒渐变渲染 */ Shader mRadialGradient = null; //------------------------------------------------------------------------------------------------------// public BallView(Context context) { super(context); // 实例化SurfaceHolder mSurfaceHolder = this.getHolder(); // 添加回调 mSurfaceHolder.addCallback(this); this.setFocusable(true); //获取屏幕宽度和高度 screen_width = BaomingActivity.screenWidth;//320 screen_height = BaomingActivity.screenHeight;//480 //砖的属性 brick_width = screen_width/5;//每块砖宽64 brick_height = screen_height/15;//每块砖高32 //挡板的属性 board_length = screen_width/4;//挡板长度:80比较合适,可以随意修改,但别超过screen_width board_left = (screen_width-board_length)/2;//挡板左侧(可变) board_right = (screen_width+board_length)/2;//挡板右侧(可变) board_thickness = 5;//挡板厚度 board_default_top = 13*screen_height/15;//即435,挡板的top面初始位置 board_alterable_top = board_default_top;//挡板上侧(可变) board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧(可变) ball_default_x = screen_width/2;//球的初始x坐标 ball_default_y = board_default_top - ball_r;//球的初始y坐标 //球的即时坐标(可变): ball_x = ball_default_x; ball_y = ball_default_y; //球的前一步的y坐标 ball_previous_y = 0; ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 mbLoop = true; ball_isRun = false; score=0; brick_exist = new boolean[25]; for (int i = 0; i < 25; i++) { brick_exist[i] = true; } /* 构建RadialGradient对象,设置半径的属性 */ mRadialGradient = new RadialGradient(ball_x, ball_y, ball_r,//球中心坐标x,y,半径r new int[]{Color.WHITE,Color.BLUE,Color.GREEN,Color.RED,Color.YELLOW},//颜色数组 null,//颜色数组中每一种颜色对应的相对位置,为空的话就是平均分布,由中心向外排布 Shader.TileMode.REPEAT);//渲染模式:重复 } public void resetGame(){ ball_isRun = false; score =0;//分数 ball_x_speed = ballXorYadd;//球的横向偏移量 ball_y_speed = ballXorYadd;//球的纵向偏移量 ball_x = screen_width/2;//球心起始横坐标 ball_y = board_default_top - ball_r;//球心起始纵坐标 board_left = (screen_width-board_length)/2;//挡板左侧 board_right = (screen_width+board_length)/2;//挡板右侧 board_alterable_top = board_default_top;//挡板上侧 board_alterable_bottom = board_alterable_top+board_thickness;//挡板下侧 for (int i = 0; i < 25; i++) { brick_exist[i] = true; } } //---------------------------------绘图循环开始---------------------------------- public void run() { while (mbLoop&&!Thread.currentThread().isInterrupted()) { try { Thread.sleep(ball_sleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } //球的前一步y坐标 ball_previous_y = ball_y; if (ball_isRun) { ballRunning();// 让小球移动 boardPositionCheck();//检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” hitWallCheck();//墙壁碰撞检测 hitBoardCheck();//挡板碰撞检测 hitBrickCheck();//砖块碰撞检测 } synchronized (mSurfaceHolder) { Draw(); } } } //---------------------------------绘图循环结束---------------------------------- //------------------------------------------------------------------------------ //让小球移动 public void ballRunning() { ball_x += ball_x_speed; ball_y -= ball_y_speed; } //朝左或朝右碰撞后小球水平方向逆向 public void ballLeftOrRightHit() { ball_x_speed *= -1; } //朝上或朝下碰撞后小球竖直方向逆向 public void ballUpOrDownHit() { ball_y_speed *= -1; } public void ballcornerHit() { ball_x_speed *= -1; ball_y_speed *= -1; } public void ballStraightUp() {//功能没实现,这是多余代码 ball_x_speed = 0;//注意在其他地方恢复 ball_y_speed *= -1; } //-------------------墙壁碰撞检测开始------------------------------------- public void hitWallCheck() { // 左碰墙 if (ball_x <= ball_r && ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); // 右碰墙 } if (ball_x >= screen_width - ball_r && //不能写为 else if,因为可能恰好碰到角落。 ball_y >= ball_r && ball_y <= screen_height) { ballLeftOrRightHit(); } // 上碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y <= ball_r + brick_height) //、、、、、、、、、、、、、、、25号修改 { ballUpOrDownHit(); } // 下碰墙 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && ball_y >= screen_height-ball_r) { ballUpOrDownHit(); if(score<=10){ score = 0; } else score-=10; } } //-------------------墙壁碰撞检测结束------------------------------------- //-----------------------------挡板碰撞检测开始--------------------------- public void hitBoardCheck() { // 下碰挡板正面 if (ball_x >= ball_r && ball_x <= screen_width - ball_r && //在屏幕内,起码条件 ball_x >= board_left && ball_x <= board_right && //在挡板X域上方 ball_y == board_alterable_top - ball_r &&//球面与挡板相切 ball_previous_y <= board_alterable_top - ball_r //确定球是从上方下落 ) { if(board_alterable_top==board_default_top-boardYadd ){//如果弹簧伸张,挡板位于上线 ballHitBoardlower();//作用:ball_y_move减小;挡板被打下;小球Y向运动反向 } else if(board_alterable_top==board_default_top){//如果弹簧压缩,挡板位于下线 boardHitBallHigher();//作用:ball_y_move增加;挡板弹上;小球Y向运动反向 } } //斜碰挡板右上角//经验证有效 else if(Math.pow(board_right-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>board_right && ball_y<board_alterable_top) { ballcornerHit(); } //斜碰挡板的左上角//经验证有效 else if(Math.pow(board_left-ball_x, 2)+Math.pow(board_alterable_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x<board_left && ball_y<board_alterable_top) { ballcornerHit(); } } //-----------------------------挡板碰撞检测结束-------------------------- private void boardHitBallHigher() {//增强 ballUpOrDownHit();//小球Y方向反向,ball_y_speed变为正数 if(ball_y_speed == ballXorYadd ){ ball_y_speed += ballXorYadd;//离开挡板后小球Y方向速度增强 } if( boardYadd > ball_y_speed ){//在线程这一轮,小球上升多少,挡板就上升多少。 board_alterable_top = board_default_top - ball_y_speed; board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } //检测挡板是否处于“中线”位置,是就随小球上升一步,直至到“上线” private void boardPositionCheck() {//还可直接利用球的位置刷新,board_top与球心相差ball_r if(board_alterable_top < board_default_top && board_alterable_top > board_default_top-boardYadd){ //挡板随球上升 if(board_alterable_top - ball_y_speed >= board_default_top-boardYadd){ board_alterable_top -= ball_y_speed;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } else{ board_alterable_top = board_default_top-boardYadd;//挡板上层面 board_alterable_bottom= board_alterable_top+board_thickness;//挡板下层面 } } } private void ballHitBoardlower() {//减弱 board_alterable_top=board_default_top; board_alterable_bottom=board_default_top+board_thickness;//挡板被打退 ballUpOrDownHit();//小球Y方向反向 if(ball_y_speed==2*ballXorYadd){ ball_y_speed -= ballXorYadd;//小球Y方向速度减弱 } } //砖块碰撞检测开始----------------------------------------------------------- public void hitBrickCheck() { for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); //朝下碰砖的top面 AAAAAAAAAAAAAAAAAAAAA if(ball_x >= brick_left && ball_x <= brick_right && ball_y >= brick_top-ball_r && ball_y < brick_top) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝下正碰2砖中间,i砖右上角检测 if(k!=5 && ball_x == brick_right)//如果不是第5列砖的右侧边 { //如果砖[i+1]存在 if(brick_exist[i+1]){ brick_exist[i+1] = false; score+=4; } } //朝下正碰2砖中间,i砖左上角检测 else if(k!=1 && ball_x == brick_left)//如果不是第1列砖的左侧边 { //如果砖[i-1]存在 if(brick_exist[i-1]){ brick_exist[i-1] = false; score+=4; } } } //朝上碰砖的bottom面 BBBBBBBBBBBBBBBBB else if(ball_x >= brick_left && ball_x <= brick_right && ball_y > brick_bottom&& ball_y <= brick_bottom + ball_r ) { ballUpOrDownHit(); brick_exist[i] = false; score+=4; //朝上正碰2块砖中间--i砖的右下角检测 if(k!=5 && ball_x == brick_right) //如果不是第5列砖的右侧边 { if(brick_exist[i+1]){//如果砖[i+1]存在 brick_exist[i+1] = false; score+=4; } } //朝上正碰2块砖中间--i砖的左下角检测 else if(k!=1 && ball_x == brick_left) //如果不是第1列砖的左侧边 { if(brick_exist[i-1]){//如果砖[i-1]存在 brick_exist[i-1] = false; score+=4; } } } //朝右碰砖的left面CCCCCCCCCCCCCCCCC else if(ball_x >= brick_left -ball_r&&ball_x < brick_left&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝右正碰2块砖中间,左下角检测 if(j!=5 && ball_y == brick_bottom)//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝右正碰2块砖中间,左上角检测 else if(j!=1 && ball_y == brick_top)//如果不是第1行砖的上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } //朝左碰砖的right面DDDDDDDDDDDDDDDDDD else if(ball_x >= brick_right && ball_x <= brick_right+ball_r&& ball_y >= brick_top && ball_y <= brick_bottom) { ballLeftOrRightHit(); brick_exist[i] = false; score+=4; //朝左正碰2块砖中间,右下角检测 if(j!=5 && ball_y == brick_bottom )//如果不是第5行砖的下侧边 { if(brick_exist[i+5]){//如果砖[i+5]存在 brick_exist[i+5] = false; score+=4; } } //朝左正碰2块砖中间,右上角检测 else if(j!=1 && ball_y == brick_top )//如果不是第1行砖上侧边 { if(brick_exist[i-5]){//如果砖[i-5]存在 brick_exist[i-5] = false; score+=4; } } } ///////////////////////////////////////// //斜碰i砖的左下角EEEEEEEEEEEEEEEEEEEEEEEE else if(( i-1<0||(i-1>=0&&!brick_exist[i-1]) ) && (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_left-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_r && ball_x<brick_left && ball_y>brick_bottom && ball_y<brick_bottom+ball_r ) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右下角FFFFFFFFFFFFFFFFFFFFFFFFFF else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i+5>=25||(i+5<25&&!brick_exist[i+5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_bottom-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right&&ball_x<brick_right+ball_r&& ball_y>brick_bottom&&ball_y<brick_bottom+ball_r ) { Log.v("----------", "right bottom hit"+i+":"+brick_exist[i]); ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的右上角GGGGGGGGGGGGGGGGGGGGGGGG else if( (i+1>=25||(i+1<25&&!brick_exist[i+1]) )&& (i-5<0||(i-5>0&&!brick_exist[i-5]) )&& Math.pow(brick_right-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_right && ball_x<brick_right+ball_r&& ball_y>brick_top-ball_r && ball_y<brick_top) { ballcornerHit(); brick_exist[i] = false; score+=4; } //斜碰i砖的左上角HHHHHHHHHHHHHHHHHHHHHHHHHH else if((i-1<0||(i-1>=0&&!brick_exist[i-1])) && (i-5<0||(i-5>=0&&!brick_exist[i-5])) && Math.pow(brick_left-ball_x, 2)+Math.pow(brick_top-ball_y,2)<=Math.pow(ball_r, 2)&& ball_x>brick_left-ball_x && ball_x<brick_left && ball_y>brick_top-ball_r && ball_y<brick_top ) { ballcornerHit(); brick_exist[i] = false; score+=4; } }//end if }//end for }//end hitBrickCheck() //砖块碰撞检测结束----------------------------------------------------------- //------------------------------------------ public boolean gameOver(){ int count = 0; for(boolean s:brick_exist){ if(!s){ count++; } } if(count == 25){ return true; }else{ return false; } } //------------------------------------------ //---------------绘图方法开始------------------------ public void Draw() { // 锁定画布,得到canvas Canvas canvas = mSurfaceHolder.lockCanvas(); if (mSurfaceHolder == null || canvas == null) { return; } // 绘图 Paint mPaint = new Paint(); // 设置取消锯齿效果 mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); // 绘制矩形--背景 canvas.drawRect(0, 0, screen_width, brick_height-2, mPaint); mPaint.setColor(Color.GREEN); // 绘制矩形--背景 canvas.drawRect(0, brick_height-2, screen_width, screen_height, mPaint); mPaint.setColor(Color.RED);//设置字体颜色 mPaint.setTextSize(brick_height-7);//设置字体大小 canvas.drawText("得分:"+score, 0, brick_height-7, mPaint); // 绘制顶层挡板````````````````````````````````````````````````````````25号修改 mPaint.setColor(Color.BLACK);//设置颜色 mPaint.setStrokeWidth(4);//设置粗细 canvas.drawLine(0, brick_height-2, screen_width, brick_height-2, mPaint); for (int i = 0; i <25 ; i++) { if (brick_exist[i]) { k = i % 5+1;// 1,2,3,4,5循环 j = i / 5+1;// 1,1,1,1,1;2,2,2,2,2,;...;5,5,5,5,5 brick_left = brick_width*(k-1); brick_right = brick_width*k; brick_top = brick_height*j; brick_bottom = brick_height*(j+1); mPaint.setStyle(Paint.Style.FILL);// 设置实心画笔 mPaint.setColor(Color.YELLOW); canvas.drawRect(brick_left+1, brick_top+1, brick_right-1,brick_bottom-1, mPaint); mPaint.setStyle(Paint.Style.STROKE);// 设置空心画笔 mPaint.setStrokeWidth(2);//设置粗细 mPaint.setColor(Color.BLUE); canvas.drawRect(brick_left+3, brick_top+3, brick_right-3,brick_bottom-3, mPaint); } } // 设置实心画笔 mPaint.setStyle(Paint.Style.FILL); { mPaint.setShader(mRadialGradient); canvas.drawCircle(ball_x, ball_y, ball_r, mPaint); } Paint mPaint2 = new Paint(); // 设置取消锯齿效果 mPaint2.setAntiAlias(true); // 设置实心画笔 mPaint2.setStyle(Paint.Style.FILL); { mPaint2.setColor(Color.BLACK); /* 绘制矩形挡板 */ canvas.drawRect(board_left, board_alterable_top, board_right, board_alterable_bottom,mPaint2); float board2_bottom = screen_height - 2*ball2_r;//164 float board2_top = board2_bottom - 4;//160 //线段端点坐标数组 float x0 = board_left+(board_right-board_left)/4; float y0 = board_alterable_bottom;//440或者444 float springAdd = (board2_top- board_alterable_bottom)/8;//即2.5或者2:弹簧小线段的y向长度 float springWidth = 5.0f;//弹簧小线段的x向长度 float x1 = x0 - springWidth; float y1 = y0 + springAdd; float x2 = x0 + springWidth; float y2 = y0 + 3*springAdd; float x3 = x1 ; float y3 = y0 + 5*springAdd; float x4 = x2; float y4 = y0 + 7*springAdd; float x5 = x0 ; float y5 = board2_top;//即460 float between_spring = (board_right-board_left)/2; float pts[] = { x0,y0,x1,y1, x1,y1,x2,y2, x2,y2,x3,y3, x3,y3,x4,y4, x4,y4,x5,y5}; float pts2[] = {x0+between_spring,y0, x1+between_spring,y1, x1+between_spring,y1, x2+between_spring,y2, x2+between_spring,y2, x3+between_spring,y3, x3+between_spring,y3, x4+between_spring,y4, x4+between_spring,y4, x5+between_spring,y5}; mPaint2.setStrokeWidth(2);//设置弹簧粗细 //绘制2个弹簧 canvas.drawLines(pts, mPaint2); canvas.drawLines(pts2, mPaint2); //绘制下层挡板 canvas.drawRect(board_left, board2_top, board_right, board2_bottom,mPaint2); mPaint2.setColor(Color.BLACK);// // 绘制最下面的两个“轮子”(圆心x,圆心y,半径r,p) canvas.drawCircle(board_left+ball2_r, screen_height-ball2_r, ball2_r, mPaint2);//圆 canvas.drawCircle(board_right-ball2_r, screen_height-ball2_r, ball2_r, mPaint2); mPaint2.setColor(Color.WHITE);// canvas.drawPoint(board_left+ball2_r, screen_height-ball2_r, mPaint2);//绘制左轮轮心 canvas.drawPoint(board_right-ball2_r, screen_height-ball2_r, mPaint2);//绘制右轮轮心 }//实心画笔mPaint2结束 if(gameOver()){ // mbLoop = false;//注释掉的话GAME OVER后也可重启 ball_isRun = false; mPaint2.setColor(Color.BLACK);//设置字体颜色 mPaint2.setTextSize(40.0f);//设置字体大小 canvas.drawText("GAME OVER", screen_width/32+40, screen_height/16*9-70, mPaint2); mPaint2.setTextSize(20.0f);//设置字体大小 canvas.drawText("Press \"MENU\" button to restart,", screen_width/32, //320/32=10 screen_height/16*9, //480/16=30,30*9=270 mPaint2); canvas.drawText("Press \"BACK\" button to exit.", screen_width/32, //320/32=10 screen_height/16*10, //480/16=30,30*10=300 mPaint2); } // 绘制后解锁,绘制后必须解锁才能显示 mSurfaceHolder.unlockCanvasAndPost(canvas); }// end of Draw() //---------------------绘图方法结束----------------------------------------------- // 在surface的大小发生改变时激发 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } // 在surface创建时激发 public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();// 开启绘图线程 } // 在surface销毁时激发 public void surfaceDestroyed(SurfaceHolder holder) { // 停止循环 mbLoop = false; } } package sen.tan; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; public class dazhuankuaiActivity extends Activity { BallView myview; public static int screenWidth ; public static int screenHeight; private TextView textview; Button kaishi,jieshu,guanyu; ImageView image; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String string = "欢迎进入疯狂打砖块游戏"; image = (ImageView) this.findViewById(R.id.image); image.setImageResource(R.drawable.img1); textview =(TextView) this.findViewById(R.id.textview); textview.setTextSize(20); textview.setTextColor(Color.GREEN); textview.setBackgroundColor(Color.RED); textview.setText(string); kaishi=(Button)findViewById(R.id.button1); guanyu=(Button)findViewById(R.id.button2); jieshu=(Button)findViewById(R.id.button3); kaishi.setWidth(250); guanyu.setWidth(200); jieshu.setWidth(150); kaishi.setTextSize(35); guanyu.setTextSize(29); jieshu.setTextSize(24); jieshu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { dazhuankuaiActivity.this.finish(); } }); guanyu.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ textview.setText("本游戏由邵明森和谭明星制作,此游戏控制左右按键,来回移动挡板,不让小球掉落,当小球把上方砖块全部打完时,游戏胜利"); } }); kaishi.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v){ public void onCreate(Bundle savedInstanceState)这里显示的错误 显示的是上面两个括号标示不对。 { super.onCreate(savedInstanceState); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); screenWidth = dm.widthPixels; screenHeight = dm.heightPixels; setTitle("宽"+screenWidth+" 高"+screenHeight); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); myview = new BallView(this); setContentView(myview); } } public boolean onTouchEvent(MotionEvent event) { return true; } public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MENU: myview.resetGame(); break; case KeyEvent.KEYCODE_DPAD_CENTER: myview.ball_isRun = !myview.ball_isRun; break; case KeyEvent.KEYCODE_DPAD_LEFT: if(myview.ball_isRun){ if(myview.board_left<=myview.board_x_move) { myview.board_left=0; myview.board_right=myview.board_length; }else{ myview.board_left-=myview.board_x_move; myview.board_right-=myview.board_x_move;} } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if(myview.ball_isRun){ if(screenWidth-myview.board_right<=myview.board_x_move ) { myview.board_left=screenWidth-myview.board_length; myview.board_right=screenWidth; }else{ myview.board_left+=myview.board_x_move; myview.board_right+=myview.board_x_move; } } break; case KeyEvent.KEYCODE_DPAD_UP: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top) { myview.board_alterable_top-=myview.boardYadd; myview.board_alterable_bottom-=myview.boardYadd; } } break; case KeyEvent.KEYCODE_DPAD_DOWN: if(myview.ball_isRun){ if( myview.board_alterable_top==myview.board_default_top-myview.boardYadd ) { myview.board_alterable_top=myview.board_default_top; myview.board_alterable_bottom=myview.board_alterable_top+myview.board_thickness; } } break; case KeyEvent.KEYCODE_BACK: this.finish(); break; } return false; } public boolean onKeyUp(int keyCode, KeyEvent event) { return true; } public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { return true; } } ); } }
求android大神指点这个效果如何实现
最近在学习android开发,想实现一个类似于京东APP商品筛选功能(如截图所示):点击activityA上的一个按钮,从屏幕右侧向左滑出一个浮动的activityB,不完全遮盖activityA,在activityB上点击确定后可以更新activityA的数据。小弟初学乍道,求大神指点用什么来实现该功能最合理最容易! ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420688031_270415.png)
安卓控制屏幕熄灭的问题
我安卓网上的方法用powermanage类但是不管用,还有那个常量被废弃了用什么代替,我是在广播接收器里的对话框的确定按钮的监听事件里写的这个代码![图片](https://img-ask.csdn.net/upload/201605/20/1463733475_683213.jpg)
android scrollview动态加载数据
先声明不是滑动加载更多数据,我要做一个订单的页面,scrollview里面的内容不确定是几条,如果里面嵌套listview,每个item的布局太复杂(包含很多按钮,edittext,下拉菜单等等),很容易冲突,而且item的高度可能超过了一屏幕,scrollview嵌套listview问题又很多,所以请高手帮忙,该如何实现!谢谢各位了!
安卓中自定义对话框的显示问题
android中自定义的dialog,为甚么会出现一块没有设置的背景呢》下面给出源码和效果图。 自定义dialog的布局xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" android:background="@drawable/custom_dialog"> <TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="提示" android:textSize="20sp" android:layout_marginTop="20dp"/> <TextView android:id="@+id/tv_message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="是否删除?" android:layout_marginBottom="20dp" android:textSize="20sp" android:layout_marginTop="20dp"/> <View android:layout_width="match_parent" android:layout_height="0.5dp" android:background="#000000" /> <LinearLayout android:layout_width="match_parent" android:layout_height="45dp" android:orientation="horizontal" > <TextView android:id="@+id/tv_confirm" android:gravity="center" android:layout_width="0dp" android:layout_height="45dp" android:layout_weight="1" android:text="确定" android:textSize="20sp" /> <View android:layout_width="0.5dp" android:layout_height="45dp" android:background="#000000" /> <TextView android:id="@+id/tv_cancel" android:gravity="center" android:layout_width="0dp" android:layout_height="45dp" android:layout_weight="1" android:text="取消" android:textSize="20sp" /> </LinearLayout> </LinearLayout> 自定义Dialog的java代码 package Dialog; import android.app.Dialog; import android.content.Context; import android.graphics.Point; import android.os.Bundle; import android.text.TextUtils; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import uilist.ldm.com.uilist.R; import static uilist.ldm.com.uilist.R.id.dialog; /** * Created by Administrator on 2017/9/20 0020. */ public class DialogStyle extends Dialog implements View.OnClickListener { private TextView tv_title,tv_message,tv_confirm,tv_cancel; private IOnCanelListener canelListener; private IOnConfirmListener confirmListener; private String title,message,confirm,cancel; public DialogStyle(Context context) { super(context); } public DialogStyle(Context context,int themeId) { super(context,themeId); } public DialogStyle setTitle(String title) { this.title = title; return this; } public DialogStyle setMessage(String message) { this.message = message; return this; } public DialogStyle setConfirm(String confirm,IOnConfirmListener listener) { this.confirm = confirm; this.confirmListener=listener; return this; } public DialogStyle setCancel(String cancel,IOnCanelListener listener) { this.cancel = cancel; this.canelListener=listener; return this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialogstyle); //设置宽度 WindowManager m=getWindow().getWindowManager(); Display d=m.getDefaultDisplay(); WindowManager.LayoutParams p=getWindow().getAttributes(); Point size=new Point(); d.getSize(size); p.width=(int)(size.x*0.8);//设置dialog的宽度为当前手机屏幕的80% getWindow().setAttributes(p); tv_title= (TextView) findViewById(R.id.tv_title); tv_message= (TextView) findViewById(R.id.tv_message); tv_confirm= (TextView) findViewById(R.id.tv_confirm); tv_cancel= (TextView) findViewById(R.id.tv_cancel); //设置文字 if(!TextUtils.isEmpty(title)){ tv_title.setText(title); } if(!TextUtils.isEmpty(message)){ tv_message.setText(message); } if(!TextUtils.isEmpty(confirm)){ tv_confirm.setText(confirm); } if(!TextUtils.isEmpty(cancel)){ tv_cancel.setText(cancel); } //设置监听 tv_confirm.setOnClickListener(this); tv_cancel.setOnClickListener(this); } public interface IOnCanelListener{ void onCancel(DialogStyle dialog); } public interface IOnConfirmListener{ void onConfirm(DialogStyle dialog); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.tv_cancel: if(canelListener!=null){ canelListener.onCancel(this); } dismiss(); break; case R.id.tv_confirm: if(confirmListener!=null){ confirmListener.onConfirm(this); } dismiss(); break; default: break; } }} 以及Dialog的shape设置 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#ffffff"/> <corners android:radius="10dp"/> </shape> activity中的监听事件 case R.id. dialog1: DialogStyle dialog=new DialogStyle(DialogListActivity.this); dialog.setTitle("提示").setMessage("确认是否删除当前内容").setCancel("取消", new DialogStyle.IOnCanelListener() { @Override public void onCancel(DialogStyle dialog) { Toast.makeText(DialogListActivity.this,"取消",Toast.LENGTH_LONG).show(); } }).setConfirm("确认", new DialogStyle.IOnConfirmListener() { @Override public void onConfirm(DialogStyle dialog) { Toast.makeText(DialogListActivity.this,"确定",Toast.LENGTH_LONG).show(); } }).show(); break; 效果图: ![图片说明](https://img-ask.csdn.net/upload/201709/20/1505893726_503231.png)
适配1080*1800资源 问题
我想适配 1080 * 1800 的这种分辨率的手机。于是我创建了一个资源文件夹: drawable-xxhdpi-1800*1080 的文件,并在文件内放置了资源。用1080 * 1800的手机运行 可以确定是用的这个文件夹下的资源,但是发现 1080*1920的也用这个文件夹下的资源了,而不是用的 xxhdpi下的资源。 我想要的结果是: 1080 * 1800用的是drawable-xxhdpi-1800 * 1080下的资源 其他的高分辨率的用的是xxhdpi的资源。 我该怎么做?
电脑如何在安卓机设置了仅充电后连接上手机获取里面的数据(绝对本人手机,因屏幕损坏无法取出照片)。
我的安卓手机设置了仅充电(关闭了usb调试,360手机助手等均无法连接),然后屏幕摔坏了(无法显示,黑屏,触摸应该也坏了)但是确定能开机,其他一切正常,里面有一些十几年前的照片,现在怎么能取出来啊,希望大神们给条路子!万分感谢!!!
关于安卓内存泄露的问题
小弟最近在做一个小项目,基本上功能完成了,但发现在程序运行了几分钟后会自动退出,打印的日志信息如下: ![图片说明](https://img-ask.csdn.net/upload/201907/22/1563795606_231565.png) 然后又通过对程序进行注释后发现在将从服务器获取数据的功能注释掉后这个问题解决了,所以觉得问题应该是出在这一块,在这个功能中循环调用的函数有关于对象以及线程,不知是否是这一块的问题,现将整个程序贴上求大神帮忙看看: MainActivity中: ``` package com.example.gsontest; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; import com.baidu.mapapi.utils.CoordinateConverter; import org.json.JSONObject; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private MapView mapView; private BaiduMap baiduMap; public LocationClient mLocationClient; public static String responseData; public double dvalueX; public double dvalueY; private boolean isFirstLocate = true; public int mXDirection; //方向类的对象 public MyOrientationListener myOrientationListener; @Override //该函数主要是进行Activity初始化 protected void onCreate(Bundle savedInstanceState) { Log.i("MainActivity","进入到onCreate函数中进行初始化"); super.onCreate(savedInstanceState); //实例化对象 mLocationClient = new LocationClient(getApplicationContext()); //注册监听器 mLocationClient.registerLocationListener(new MyLocationListener()); //初始化SDK SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); mapView = (MapView) findViewById(R.id.bmpView); baiduMap = mapView.getMap(); baiduMap.setMyLocationEnabled(true); //尝试在监听按钮之前进行权限的允许 List<String> permissionList = new ArrayList<>(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.READ_PHONE_STATE); } if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (!permissionList.isEmpty()) { String[] permission = permissionList.toArray(new String[permissionList.size()]); ActivityCompat.requestPermissions(MainActivity.this, permission, 1); requestLocation(); } else { requestLocation(); } } private void requestLocation() { Log.i("MainActivity", "进入到requestLocation函数中"); initLocation(); //定位开始 initOrientationListener(); myOrientationListener.start(); mLocationClient.start(); } private void initLocation() { Log.i("MainActivity", "跳进了initLocation定位初始化函数中"); LocationClientOption option = new LocationClientOption(); option.setCoorType("bd09ll"); option.setScanSpan(1000); mLocationClient.setLocOption(option); } private void initOrientationListener() { Log.i("MainActivity", "跳进了initOrientationListener方向初始化函数中"); myOrientationListener = new MyOrientationListener(getApplicationContext()); myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() { @Override public void onOrientationChanged(float x) { mXDirection = (int) x; } }); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { Log.i("MainActivityActivity","进入onRequestPermissionResult函数中"); switch (requestCode) { case 1: if (grantResults.length > 0) { for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "必须同意所有权限", Toast.LENGTH_LONG).show(); finish(); return; } } // sendRequestWithOkHttp(); } else { Toast.makeText(this, "发生未知错误", Toast.LENGTH_LONG).show(); finish(); } break; default: } } //定位监听器的类 public class MyLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { Log.i("MainActivity", "跳进了onReceiveLocation函数中"); if (location.getLocType() == BDLocation.TypeGpsLocation || location.getLocType() == BDLocation.TypeNetWorkLocation) { navigateTo(location); } } } private void navigateTo(BDLocation location) { Log.i("MainActivity", "跳进了navigateTo函数中"); //从服务器上获取实时的硬件位置 sendRequestWithOkHttp(); //将获取到的数据进行解析 ObjectJson(responseData); //将获取到的经纬度信息在地图上进行显示 displayLocation(dvalueX, dvalueY); //初次定位确定缩放尺寸,后面不改变便于手动伸缩 if (isFirstLocate) { BitmapDescriptor myBitMap = BitmapDescriptorFactory.fromResource(R.drawable.icon_reddirection); MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, myBitMap); baiduMap.setMyLocationConfiguration(myLocationConfiguration); LatLng la = new LatLng(location.getLatitude(), location.getLongitude()); MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(la); baiduMap.animateMapStatus(update); update = MapStatusUpdateFactory.zoomTo(18f); baiduMap.animateMapStatus(update); isFirstLocate = false; } //将手机当前位置的小蓝点显示在屏幕上 MyLocationData.Builder locationBuilder = new MyLocationData.Builder(); locationBuilder.latitude(location.getLatitude()); locationBuilder.longitude(location.getLongitude()); //将要执行获取方向方法 locationBuilder.direction(mXDirection); MyLocationData locationData = locationBuilder.build(); baiduMap.setMyLocationData(locationData); } //重写三个方法以对mapView进行管理,保证资源可以及时释放 @Override protected void onResume() { Log.i("MainActivity", "进入到onResume函数中"); super.onResume(); mapView.onResume(); } @Override protected void onPause() { Log.i("MainActivity", "进入到onPause函数中"); super.onPause(); mapView.onPause(); } @Override protected void onDestroy() { Log.i("MainActivity", "进入到onDestroy函数中"); super.onDestroy(); mapView.onDestroy(); baiduMap.setMyLocationEnabled(false); mLocationClient.stop(); //停止方向监听 myOrientationListener.stop(); } private void sendRequestWithOkHttp() { Log.i("MainActivity", "跳进了sendRequestWithOkHttp方法中"); new Thread(new Runnable() { @Override //重写run方法,run方法规定了该线程的具体使命 public void run() { Log.i("MainActivity","跳进OkHttp的子线程中"); try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://huadiheal.cn/animal/latest_data") .build(); Response response = client.newCall(request).execute(); responseData = response.body().string(); // ObjectJson(responseData); } catch (Exception e) { e.printStackTrace(); } } //创建后线程仅是占有内存资源,在JVM管理的线程中还没有这个资源,要调用父类的start方法通知JVM }).start(); } private void ObjectJson(String responseData) { Log.i("MainActivity", "跳进了ObjectJson函数中"); try { JSONObject jsonObject = new JSONObject(responseData); JSONObject valueX = jsonObject.getJSONObject("value_x"); JSONObject valueY = jsonObject.getJSONObject("value_y"); Iterator<String> iteratorX = valueX.keys(); while (iteratorX.hasNext()) { String valueXkey = iteratorX.next(); String valueXValue = valueX.getString(valueXkey); String valueYValue = valueY.getString(valueXkey); dvalueX = Double.parseDouble(valueXValue); dvalueY = Double.parseDouble(valueYValue); } } catch (Exception e) { e.printStackTrace(); } } public void displayLocation(double dvalueX, double dvalueY) { Log.i("MainActivity", "进入displayLocation中"); LatLng latLng = new LatLng(dvalueY, dvalueX); //进行坐标转换 CoordinateConverter converter = new CoordinateConverter() .from(CoordinateConverter.CoordType.GPS) .coord(latLng); LatLng dLatlng = converter.convert(); //进行刷新时,先清除上一次的overlay baiduMap.clear(); //现添加Marker将位置在地图上标出来 BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_niu32); OverlayOptions option = new MarkerOptions() .position(dLatlng) .icon(bitmap); baiduMap.addOverlay(option); } } ``` 方向传感器的监听类如下: ``` package com.example.gsontest; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.util.Log; //方向监听器的类 public class MyOrientationListener implements SensorEventListener { private SensorManager mySensorManager; private Sensor mySensor; private Context myContext; private float lastX; private OnOrientationListener myOnOrientationListener; public void start(){ Log.i("MainActivity", "跳进了方向类的start函数中"); mySensorManager = (SensorManager) myContext.getSystemService(Context.SENSOR_SERVICE); if(mySensorManager!=null){ mySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } if(mySensor!=null){ //SENSOR_UI可能会出现数据滞后现象,若后期数据滞后则改成别的类型 mySensorManager.registerListener(this,mySensor,SensorManager.SENSOR_DELAY_NORMAL); } } //接触注册方向传感器监听事件,即对onDestroy中所引方法的实现 public void stop(){ Log.i("MainActivity","跳进方向类的stop函数中"); mySensorManager.unregisterListener(this); } //方向传感器的一个构造函数 public MyOrientationListener(Context myContext){ this.myContext = myContext; } @Override public void onAccuracyChanged(Sensor sensor,int accuracy){} //监听方向变化 @Override public void onSensorChanged(SensorEvent event){ Log.i("MainActivity","跳进了onSensorChanged函数中"); if(event.sensor.getType()==Sensor.TYPE_ORIENTATION){ float x = event.values[SensorManager.DATA_X]; if (Math.abs(x-lastX)>1.0){ if(myOnOrientationListener!=null){ myOnOrientationListener.onOrientationChanged(lastX); } } lastX = x; } } public void setOnOrientationListener(OnOrientationListener myOrientationListener){ this.myOnOrientationListener = myOrientationListener; } public interface OnOrientationListener{ void onOrientationChanged(float x); } } ``` 恳请大神帮忙看下程序谢谢!!
在onTouchEvent()时间里面加了一个scale 缩放动画效果,效果和预期不同
//设置动画属性 animation = new ScaleAnimation(1.0f, 0.5f, 1.0f, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(500);// 设置动画持续时间 animation.setRepeatCount(1);// 设置重复次数 animation.setRepeatMode(Animation.REVERSE); //onTouchEvent()事件 public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: int width = iv.getWidth(); int height = iv.getHeight(); iv.setX(event.getX() - (width/2) );//iv是图片所在的imageView控件 iv.setY(event.getY() - (height/2) ); iv.startAnimation(animation); break; } return true; } 就是想实现一个类似相机手动点击聚焦的动画效果,但是实际效果是在点击屏幕后动画位置能确定,但是缩放中心是变化的,并不是设置的图片的中心点,请有经验的人帮忙指出问题,多谢!
Hbuilder小米5S无法真机调试
错误提示如下: 正在建立手机连接... 正在安装手机端HBuilder调试基座... pkg: /data/local/tmp/android_base.apk 安装失败,失败原因:Failure [INSTALL_CANCELED_BY_USER]。 请手动点亮手机屏幕,并重新运行真机调试,注:可能需要在手机上确认安装
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
C语言荣获2019年度最佳编程语言
关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang近日,TIOBE官方发布了2020年1月编程语言排行榜单。我在前面给过一篇文章《2019年11月C语言接近Ja...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
一份王者荣耀的英雄数据报告
咪哥杂谈本篇阅读时间约为 6 分钟。1前言前一阵写了关于王者的一些系列文章,从数据的获取到数据清洗,数据落地,都是为了本篇的铺垫。今天来实现一下,看看不同维度得到的结论。2环境准备本次实...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
立即提问