Android中的摇一摇实现


   有的应用中需要实现摇一摇签到,摇一摇抽奖等功能,由于App业务需要,也实现了摇一摇,总结一下。实现的界面效果如下:

布局文件如下:

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">
   

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="center"
        android:text="Hello World!" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="你在别人眼中的样子:(哈哈)"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="150dp"
        android:layout_gravity="center"
        android:layout_height="140dp" />
LinearLayout>


Activity中的代码实现如下:
package heros.com.xin.yaoyiyaodemo;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity implements SensorEventListener {

   
    private TextView mTvtext;
    private SensorManager sensorManager;
    private Vibrator vibrator;
    private ViewPager mPager;
//这个数据是从接口获取的
 private ArrayList mAdvDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvtext = (TextView) findViewById(R.id.tv_text);
        mPager = (ViewPager) findViewById(R.id.pager);

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    /**
     * 调用接口获取的数据
     */
    private void getInvestPicFromNet() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("adType", 2 + "");
        params.addBodyParameter("adPosition", 6 + "");
        params.addBodyParameter("packageName", StringUtils.PACKAGENAME);
        MyHttpUtils.getUtils().send(HttpRequest.HttpMethod.POST, "http:.../adv/getAdvList",
                params, new RequestCallBack() {
                    @Override
                    public void onSuccess(ResponseInfo responseInfo) {
                        String temp = StringUtils.processJSON(responseInfo.result);
                        System.out.println("WDYQNewActivity----getPic--------------" + temp);
                        Gson gson = new Gson();
                        GetAdvListBean advBean = gson.fromJson(temp, GetAdvListBean.class);
                        if (advBean.result == 200) {

                            if (!advBean.Advertise.isEmpty()) {
                                mAdvDatas = advBean.Advertise;
                                mPager.setAdapter(new PicAdapter (getApplicationContext(), mAdvDatas));
                            } else {
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), advBean.resultMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                    }

                });
    }

    /**
     * 随机生成的图片
     */
    private void getadapterYourPic() {
        Random random = new Random();
        int num = random.nextInt(10);
        num += 1;
        if (num > 0 && num < 3) {
//所需图片请自行添加到mipmap里
 mPager.setBackgroundResource(R.mipmap.labixiaoxin);
        } else if (num >= 3 && num < 5) {
            mPager.setBackgroundResource(R.mipmap.meinv);
        } else if (num >= 5 && num < 8) {
            mPager.setBackgroundResource(R.mipmap.nan);
        } else {
            mPager.setBackgroundResource(R.mipmap.xwz);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int sensorType = event.sensor.getType();
        float[] values = event.values;
        if (sensorType == Sensor.TYPE_ACCELEROMETER) {
            if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math.abs(values[2]) > 17)) {
                mTvtext.setText("success");
                   //调用接口的方法,有需要的可自行添加自己的接口数据进行调用,此接口获取到的只是图片信息
 //                getInvestPicFromNet();
                getadapterYourPic();
                vibrator.vibrate(500);
            }
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

========================================================================================
分割线,如果你不使用接口获取数据,只是简单实验,
 
  
 getadapterYourPic();就可以实现效果,


接口的时候会使用到Bean对象和Adapter对象:

Bean对象代码:
package heros.com.xin.yaoyiyaodemo;

import java.io.Serializable;
import java.util.ArrayList;

public class GetAdvListBean {


    public int result;
    public String resultMsg;
    public ArrayList Advertise;


    public static class AdvertiseEntity implements Serializable {

        public int Id;
        public String adLabel;
        public String adLink;
        public String adImg;
        public String adAlt;

    }
}


Adapter对象代码:
package heros.com.xin.yaoyiyaodemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.lidroid.xutils.BitmapUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class PicAdapter extends PagerAdapter {

    private Context context;

    private BitmapUtils bitmapUtils;
    private ArrayList mDrawableList;


    public WdYqPicAdapter(Context context, ArrayList mDrawableList) {
        this.context = context;
        // 初始化图片加载工具
        bitmapUtils = new BitmapUtils(context);
        this.mDrawableList = mDrawableList;
    }

    @Override
    public int getCount() {
        return mDrawableList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {


        ImageView image = new ImageView(context);

        image.setScaleType(ImageView.ScaleType.FIT_XY);

        // 获取网络图片
        bitmapUtils.display(image, mDrawableList.get(position).adImg);
        container.addView(image);
        return image;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    /**
     * 从指定URL获取图片
     * @param url
     * @return
     */
    private Bitmap getImageBitmap(String url) {
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            imgUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
 

 

 


你可能感兴趣的:(Android)