将加速计应用于移动textview

时间:2013-05-17 21:47:45

标签: android textview accelerometer

可以用accelometer移动textview吗? 即时尝试并获得forceclose

slidame4.java

public class Slidame4 extends Activity implements SensorEventListener {

    private Bitmap bit,bi,bitm;
    private TableRow tblrow ;
    private ImageView bimg;
    private kotak hitam;
    private TextView v ;
    private List<kotak> tiles = null;
    private List<TileView> tileViews = null;
    private List<TableRow> tableRow = null;
    private TableLayout tbl;
    public int ukurangrid;
    private SensorManager sensorManager;

    private GameBoard coba;
    private int lebar;
    private Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Resources r = getResources();

        tbl = (TableLayout)findViewById(R.id.TableLayout1);
        tblrow = new TableRow(this);

        v= new TextView(this);
        bimg = new ImageView(this);     
        //sensor
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
        //lebar
        Display display = getWindowManager().getDefaultDisplay();
        lebar = (display.getWidth());       
        setContentView(R.layout.activity_slidame4);
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.slidame4, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item){

        switch (item.getItemId()) {
        case R.id.hint:
            Toast.makeText(getApplicationContext(), ""+lebar, Toast.LENGTH_SHORT).show();
            break;
        case R.id.highscore:
            Toast.makeText(getApplicationContext(), "HIGH SCORE ", 3).show();
            break;
        case R.id.grid3:
            ukurangrid = 3;
            createGameBoard();
            item.setChecked(true);
            break;
        case R.id.grid4:
            ukurangrid = 4;
            createGameBoard();
            item.setChecked(true);
            break;
        case R.id.grid5:
            ukurangrid = 5;
            createGameBoard();
            item.setChecked(true);
            break;

        default:
            return super.onOptionsItemSelected(item);

        }

        return false;

    }


    private final void createGameBoard() {
        TableLayout gLayout;
        gLayout = (TableLayout) findViewById(R.id.TableLayout1);
        gLayout.removeAllViews();
        bi = BitmapFactory.decodeResource(getResources(), R.drawable.gambar);
        coba = new GameBoard(this, bi, gLayout, lebar,ukurangrid);
        bi.recycle();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }
    @Override
      public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float[] values = event.values;
            // Movement
            int x = (int)values[0];
            int y = (int)values[1];
            int z = (int)values[2];
            coba.gerak(x, y, z);

        }

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

gameboard.java

public class GameBoard extends Activity  {
    private Bitmap bit;
    private int layar,lebar_board,grid,x,y,z;
    private Context context;
    private GamePiece emptyGamePiece;
    private SensorManager sensorManager;
    private static GameBoard board=null;
    private TableLayout gameLayout; 
    private List<GamePiece> gamePieces = null;
    private List<TableRow> tableRow = null;

    GameBoard(Context context, Bitmap bit, TableLayout gLayout,int lebar,int grid) {
        this.context =context;
        this.lebar_board=lebar;
        this.bit = Bitmap.createScaledBitmap(bit, this.lebar_board,
                this.lebar_board, true);
        this.gameLayout = gLayout;
        this.grid=grid;
        init();
        // TODO Auto-generated constructor stub
    }

    private void init() {
        initializeLists();
        createGamePieces();
        addToGameScreen();
    }

    private void initializeLists() {
        if (gamePieces == null) {
            gamePieces = new ArrayList<GamePiece>(grid*grid);
        } else {
            for (int i = 0; i < gamePieces.size(); i++) {
                gamePieces.get(i).getBitmap().recycle();
                gamePieces = new ArrayList<GamePiece>(grid*grid);
            }
        }

        tableRow = new ArrayList<TableRow>(grid);

        for (int row = 0; row < (grid*grid); row++) {
            tableRow.add(new TableRow(context));
        }
    }

    private void createGamePieces() {
        int gamePiece_width = bit.getWidth() / grid;
        int gamePiece_height = bit.getHeight() / grid;

        for (int row = 0; row < grid; row++) {
            for (int column = 0; column < grid; column++) {
                Bitmap bitm = Bitmap.createBitmap(bit, column
                        * gamePiece_width, row * gamePiece_height,
                        gamePiece_width, gamePiece_height);
                if ((row == grid - 1) && (column == grid - 1)) {
                    bitm = Bitmap.createBitmap(gamePiece_width, gamePiece_height,
                            bitm.getConfig());
                    bitm.eraseColor(Color.BLACK);
                    emptyGamePiece = new GamePiece(context, bitm, row, column,row + "-" + column);
                    gamePieces.add(emptyGamePiece);
                } else {
                    GamePiece tempGamePiece = new GamePiece(context, bitm, row,
                            column, row + "-" + column);
                    gamePieces.add(tempGamePiece);
                }
            } // end column
        }// end row
        bit.recycle();
    }

    public void addToGameScreen() {
        TextView cek = new TextView(context);
        cek.setText(x+"  "+y);
        Iterator<GamePiece> it = (shuffleGamePieces()).iterator();
        for (int row = 0; row < grid; row++) {
            for (int column = 0; column < grid; column++) {
                tableRow.get(row).addView(it.next());
            } // end column
            gameLayout.addView(tableRow.get(row));
        } // end row
        gameLayout.addView(cek);
    }

    public List<GamePiece> shuffleGamePieces() {
        Collections.shuffle(gamePieces);
        gamePieces.remove(emptyGamePiece);
        gamePieces.add(emptyGamePiece);

        for (int row = 0; row < grid; row++) {
            for (int column = 0; column < grid; column++) {
                gamePieces.get(grid * row + column).setCurrent(row, column);
            }
        }
        //numberOfMoves = 0;
        return gamePieces;
    }

    public static void createGameBoard(Context context, Bitmap bit,
            TableLayout gLayout, int lebar, int grid) {
        board = new GameBoard(context,bit,gLayout,lebar,grid);
    }

    public void gerak(int x,int y,int z){
        this.x=x;
        this.y=y;
        this.z=z;
            }
}

在这种情况下gerak(x,y,z)试图获得accelometer的值,我放入gameboard.java 并得到forceclose


logcat的

05-18 04:22:43.619: E/AndroidRuntime(27662): java.lang.NullPointerException
05-18 04:22:43.619: E/AndroidRuntime(27662):    at skripsi.slidame4.Slidame4.onSensorChanged(Slidame4.java:192)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at android.os.Looper.loop(Looper.java:137)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at android.app.ActivityThread.main(ActivityThread.java:4931)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at java.lang.reflect.Method.invokeNative(Native Method)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at java.lang.reflect.Method.invoke(Method.java:511)
05-18 04:22:43.619: E/AndroidRuntime(27662):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)

1 个答案:

答案 0 :(得分:0)

查看您的coba变量。

您只能使用createGameBoard();方法创建它。

只有在按下菜单并选择一些选项后才会调用此方法。

但是,您要在SensorListener方法中注册OnCreate

查看您的OnSensorChanged方法:

@Override
public void onSensorChanged(SensorEvent event) {
   if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float[] values = event.values;
        // Movement
        int x = (int)values[0];
        int y = (int)values[1];
        int z = (int)values[2];
        coba.gerak(x, y, z); // Look here.
    }
}

如果您在OnCreate中注册SensorListener,则在之前创建coba变量。因此,在创建GameBoard之前,可以将此方法(OnSensorChanged)称为

在监听器注册后,几乎每毫秒都会调用OnSensorChanged。

你在做什么?

活动创建 - &gt;传感器监听器已注册 - &gt; GameBoard创作

真正发生了什么?

活动创建 - &gt;传感器监听器已注册 - &gt; OnSensorChanged名为 - &gt; GameBoard创作

你可以做什么?

仅检查是否已创建GameBoard或创建变量以指示游戏是否已启动。

替补1:

@Override
public void onSensorChanged(SensorEvent event) {
   if (coba != null && event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float[] values = event.values;
        // Movement
        int x = (int)values[0];
        int y = (int)values[1];
        int z = (int)values[2];
        coba.gerak(x, y, z);
    }
}

替补2:

private boolean isGameInitialized = false;    

private final void createGameBoard() {
    TableLayout gLayout;
    gLayout = (TableLayout) findViewById(R.id.TableLayout1);
    gLayout.removeAllViews();
    bi = BitmapFactory.decodeResource(getResources(), R.drawable.gambar);
    coba = new GameBoard(this, bi, gLayout, lebar,ukurangrid);
    bi.recycle();
    this.isGameInitialized = true;
}

@Override
public void onSensorChanged(SensorEvent event) {
   if (this.isGameInitialized && event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        float[] values = event.values;
        // Movement
        int x = (int)values[0];
        int y = (int)values[1];
        int z = (int)values[2];
        coba.gerak(x, y, z);
    }
}