its possible to moving textview with accelometer?
im trying and get 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;
}
}
in this case gerak(x,y,z) is trying to get value of accelometer and i put in gameboard.java
and got 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)
Look to your coba variable.
You create it only in the createGameBoard(); method.
This method is called only after you press the menu and select some options.
But, you are registering your SensorListener in the OnCreate method.
Look to your OnSensorChanged method:
#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.
}
}
If you are registering your SensorListener in the OnCreate, you have it before you create your coba variable. So, this method (OnSensorChanged) can be called before your GameBoard creation.
The OnSensorChanged is called almost every millisecond after the listener is registered.
What are you doing?
Activity Creation -> Sensor Listener Registered -> GameBoard creation
What is really happening?
Activity Creation -> Sensor Listener Registered -> OnSensorChanged called -> GameBoard creation
What you can do?
only check if the GameBoard is created or create a variable to indicate if the game is started.
Alt 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);
}
}
Alt 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);
}
}
Related
I am working on a small game with touch-motion, bluetooth, and menus. At the moment the code is implemented is in my custom View.
For example vectors of classes that store game-data, vectors for current data and later will there be some threads for animations and timers.
Yet there is no icons for "abilities", but I will implement them too.
Later will there be a process or a service with bluetooth which also calls methods which are at the moment in the custom view class.
I suppose this is a bad design - so I have no concrete idea how I can or should move my functions to for example the activity which holds the custom view and how to let the custom view and activity communicate with each other.
Maybe some of you have advice on what to do.
Here is the activity:
Gamecontroller_Activity:
public class Gamecontroller_Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Enter Function","Enter onCreate Gamecontroler_Activity");
setContentView(R.layout.activity_gamecontroller);
}
}
activity_gamecontroller.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.calma.Gamecontroller_View
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
And the big custom view class (shorted) Gamecontroller_View.java:
public class Gamecontroller_View extends View implements OnGestureListener{
//Touch
private PointF fingerpointer;
private int totalClickt;
private static final int SIZE = 60;
private Paint mPaint;
//Text Flashes
private Paint textPaint;
private Paint textPaintAction;
private String currentMsg;
private boolean currentMsgShow;
//Drawables (Pictures)
private int monsterscale;
private int monsterMinimumBorderX;
private int monsterMinimumBorderY;
private Bitmap bitmap1,bitmap2;
private HashMap<String, Bitmap> hashmapMonsterStandartBitmap;
Display Informations;
private DisplayMetrics displayMetrics;
private int xDisplayMaximum;
private int yDisplayMaximum;
//Monsters
private Vector<Monster> currentMonsters;
private int monsterCountGlobal;
//Player Stats
private Player playerMe;
//Enemy Player Stats
private Player playerEnemy;
public Gamecontroller_View(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public void initView(){
//display
displayMetrics = new DisplayMetrics();
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
float displayPixelFactor = displayMetrics.widthPixels/displayMetrics.densityDpi;
xDisplayMaximum = displayMetrics.widthPixels ;
yDisplayMaximum = displayMetrics.heightPixels - (3*getStatusBarSizes());
Log.i("Display","displaywidthpixels/displayMetrics: "+xDisplayMaximum);
//yDisplayMaximum
//Enemy Player
playerEnemy = new Player();
//Monsters
monsterscale =10;
monsterMinimumBorderX= Math.min(xDisplayMaximum,yDisplayMaximum)/monsterscale;
monsterMinimumBorderY= Math.max(xDisplayMaximum,yDisplayMaximum)/monsterscale;
hashmapMonsterStandartBitmap = new HashMap<String,Bitmap>();
currentMonsters = new Vector<Monster>();
monsterCountGlobal = 0;
Log.i("display","Monsterscale: "+monsterscale + " minMonsterBorder: "+monsterMinimumBorderX);
//init Touch detection and draw
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(Color.BLUE);
mPaint.setMaskFilter(new BlurMaskFilter(15, Blur.OUTER));
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
//init Text wich will be drawn
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(30);
textPaintAction = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaintAction.setTextSize(60);
currentMsg = "";
currentMsgShow = false;
//Futher init stuff
initPlayerMe();
initPlayerEnemy();
enemySpawn();
preloadImages();
showDebug();
}
public void initPlayerMe(){
//Player
playerMe = new Player();
playerMe.setlife(100);
playerMe.setMoney(0);
playerMe.setStrength(1);
}
public void initPlayerEnemy(){
//Player
playerEnemy = new Player();
playerEnemy.setlife(100);
playerEnemy.setMoney(0);
playerEnemy.setStrength(1);
}
public Vector<Dimension> findPlaceForMonsters(int n){
//First Collect allready existing Monster Coordinates
Vector <Dimension> currentPlaces = new Vector<Dimension>();
Vector <Dimension> newPlaces = new Vector<Dimension>();
for(int i = 0; i< currentMonsters.size();i++){
if (currentMonsters.elementAt(i) != null){
currentPlaces.add(currentMonsters.elementAt(i).getDimension());
}
}
for (int i=0; i < n ;i++){
newPlaces.add(new Dimension(getRandomNumberBetween(0, xDisplayMaximum-monsterMinimumBorderX),
getRandomNumberBetween(0, yDisplayMaximum-monsterMinimumBorderY)));
Log.i("randomPlaces","Point xy: " + newPlaces.lastElement().getX()+ " "+newPlaces.lastElement().getY());
}
Log.i("findPlfaceForMonsters",this.monsterMinimumBorderX+" "+this.monsterMinimumBorderY);
return newPlaces;
}
public void enemySpawn(){
int tempCount =0;
Vector<Dimension> newPlaces = findPlaceForMonsters(6);
for(int i=0; i < 2;i++){
currentMonsters.add(new MonsterMedium(monsterCountGlobal));
currentMonsters.lastElement().setDimension(new Dimension(newPlaces.elementAt(tempCount).getX(),newPlaces.elementAt(tempCount).getY(),monsterMinimumBorderX,monsterMinimumBorderY));
monsterCountGlobal++;
tempCount++;
}
for(int i=0; i < 2;i++){
currentMonsters.add(new MonsterSmall(monsterCountGlobal));
currentMonsters.lastElement().setDimension(new Dimension(newPlaces.elementAt(tempCount).getX(),newPlaces.elementAt(tempCount).getY(),monsterMinimumBorderX,monsterMinimumBorderY));
monsterCountGlobal++;
tempCount++;
}
for(int i=0; i < 2;i++){
currentMonsters.add(new MonsterHeavy(monsterCountGlobal));
currentMonsters.lastElement().setDimension(new Dimension(newPlaces.elementAt(tempCount).getX(),newPlaces.elementAt(tempCount).getY(),monsterMinimumBorderX,monsterMinimumBorderY));
monsterCountGlobal++;
tempCount++;
}
}
public void attackMonster(int id){
for (int i=currentMonsters.size()-1; i >= 0; i--){
if (currentMonsters.elementAt(i).getID() == id){
int restlife = currentMonsters.elementAt(i).setDamge(this.playerMe.getStrength());
lifeOfMonsterChanged(currentMonsters.elementAt(i).getID(),i,restlife);
break;
}
}
}
public void lifeOfMonsterChanged(int id,int index, int life){
if (life <= 0){
Log.i("MonsterTouchted", "Monster tot");
currentMonsters.removeElementAt(index);
}
else{
Log.i("MonsterTouchted", "Monster "+id+" restlife: "+life);
//effekte? (shake?) farbE?
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// get pointer index from the event object
int pointerIndex = event.getActionIndex();
// get pointer ID
int pointerId = event.getPointerId(pointerIndex);
Log.i("touch","event.getPointerID(): "+pointerId);
// get masked (not specific to a pointer) action
int maskedAction = event.getActionMasked();
switch (maskedAction) {
//Detection of a finger touch
case MotionEvent.ACTION_DOWN:
totalClickt = totalClickt+1;
//attackTheMonster(currentPlayer.attack());
fingerpointer = new PointF();
fingerpointer.x = event.getX(0);
fingerpointer.y = event.getY(0);
for (int i=currentMonsters.size()-1; i >= 0; i--){
if(currentMonsters.elementAt(i).getDimension().contains((int)fingerpointer.x, (int)fingerpointer.y)){
Log.i("MonsterTouchted","MonsterTouched: index: "+i);
attackMonster(currentMonsters.elementAt(i).getID());
break;
}
}
case MotionEvent.ACTION_POINTER_DOWN:
{
// Optional more than one finger
break;
}
case MotionEvent.ACTION_MOVE:
{ // a pointer was moved
if (fingerpointer != null) {
fingerpointer.x = event.getX(0);
fingerpointer.y = event.getY(0);
}
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL: {
fingerpointer = null;
break;
}
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw all pointers
if (fingerpointer != null){
mPaint.setColor(colors[0]);
canvas.drawCircle(fingerpointer.x, fingerpointer.y, SIZE, mPaint);
}
// draw mosnters
for(int i=0; i < currentMonsters.size();i++){
if( currentMonsters.elementAt(i) != null){
canvas.drawBitmap(hashmapMonsterStandartBitmap.get(currentMonsters.elementAt(i).getImagePath()), currentMonsters.elementAt(i).getDimension().getX(), currentMonsters.elementAt(i).getDimension().getY(), mPaint); //bitmap, abstand left, abstand top, paint
} else{
Log.i("Failure","Draw monster nullpointer bei index: "+i);
}
}
//draw extra texts
if(currentMsgShow){
Log.i("onDraw","enter currenMsgShow");
if(displayMetrics != null){
int textsize = (int) textPaintAction.measureText(currentMsg);
int sidespacing = (displayMetrics.widthPixels - textsize)/2;
canvas.drawText(currentMsg, sidespacing, displayMetrics.heightPixels/5 , textPaintAction);
}
}
//Draw extratext
canvas.drawText( "Total Clickt: " + totalClickt, 10, 40 , textPaint);
}
}
Project:
Make those changes:
1) in your activity_gamecontroller.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.calma.Gamecontroller_View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myGameController"/>
</RelativeLayout>
2) in your Gamecontroller_Activity:
public class Gamecontroller_Activity extends Activity {
Gamecontroller_View mGameControllerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Enter Function","Enter onCreate Gamecontroler_Activity");
setContentView(R.layout.activity_gamecontroller);
mGameControllerView = (Gamecontroller_View) findViewById(R.id.myGameController);
}
}
3) now you can call for example mGameControllerView.initPlayerMe(); from any method in your Gamecontroller_Activity .
This is an example:
public class Gamecontroller_Activity extends Activity {
Gamecontroller_View mGameControllerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Enter Function","Enter onCreate Gamecontroler_Activity");
setContentView(R.layout.activity_gamecontroller);
mGameControllerView = (Gamecontroller_View) findViewById(R.id.myGameController);
testMethod();
}
private void testMethod(){
mGameControllerView.enemySpawn();
}
}
I'm developing a simple game like BSD robots. This game contains a rather large board (over 40 cells) and it doesn't look nice even at 10 inch tablet. My decision was to scroll (move) surface view and not to scale each figure which size is like finger spot.
I've read tons articles about surface view but I cannot understand how to move it?
My activity code:
package ru.onyanov.robots;
public class MainActivity extends Activity {
public BoardView board;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
board = new BoardView(this);
setContentView(board);
}
}
Class Board:
package ru.onyanov.robots;
public class BoardView extends SurfaceView {
private GameThread mThread;
private boolean running = false;
public final int sizeX = 50;
public final int sizeY = 35;
public final int cellSize = 64;
private int robotCount = 4;
public ArrayList<Cell> cells = new ArrayList<Cell>();
private ArrayList<Robot> robots = new ArrayList<Robot>();
private Hero hero;
public Bitmap imageCell;
public Bitmap imageRobot;
public Bitmap imageHero;
public BoardView(Context context) {
super(context);
makeGraphic();
constructCells();
constructRobots();
hero = new Hero(this, 3, 2, imageHero);
mThread = new GameThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
mThread.setRunning(true);
mThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
}
private void makeGraphic() {
Bitmap cellImageSource = BitmapFactory.decodeResource(getResources(),
R.drawable.cell);
imageCell = Bitmap.createScaledBitmap(cellImageSource, cellSize,
cellSize, false);
imageRobot = BitmapFactory.decodeResource(getResources(),
R.drawable.robot);
imageHero = BitmapFactory.decodeResource(getResources(),
R.drawable.hero);
}
private void constructRobots() {
Robot robot;
Random rand = new Random();
for (int r = 0; r < robotCount; r++) {
int x = rand.nextInt(sizeX);
int y = rand.nextInt(sizeY);
robot = new Robot(this, x, y, imageRobot);
robots.add(robot);
}
return;
}
private void constructCells() {
Cell cell;
for (int y = 0; y < sizeY; y++) {
for (int x = 0; x < sizeX; x++) {
cell = new Cell(this, x, y, imageCell);
cells.add(cell);
}
}
return;
}
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
Cell cell;
for (int c = 0; c < cells.size(); c++) {
cell = cells.get(c);
cell.onDraw(canvas);
}
Robot robot;
for (int r = 0; r < robots.size(); r++) {
robot = robots.get(r);
robot.onDraw(canvas);
}
hero.onDraw(canvas);
}
public boolean onTouchEvent(MotionEvent e) {
int shotX = (int) e.getX();
int shotY = (int) e.getY();
if (e.getAction() == MotionEvent.ACTION_MOVE){
//TODO move board
showToast("move Board");
} else if (e.getAction() == MotionEvent.ACTION_UP) {
showToast("touchPoint: " + shotX + ", "+shotY);
hero.moveByDirection(shotX, shotY);
this.scrollTo(shotX, shotY);
}
return true;
}
public void showToast(String mes) {
Toast toast = Toast.makeText(getContext(), mes, Toast.LENGTH_LONG);
toast.show();
}
public class GameThread extends Thread {
private BoardView view;
public GameThread(BoardView view) {
this.view = view;
}
public void setRunning(boolean run) {
running = run;
}
public void run() {
while (running) {
Canvas canvas = null;
try {
canvas = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
onDraw(canvas);
}
canvas.scale(300, 300);
} catch (Exception e) {
} finally {
if (canvas != null) {
view.getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
}
}
Some magic digits here are temporary. Now I just want to move BoardView;
The issue was to add x and y fields to SurfaceView, change them at onTouchEvent and draw all the elements in canvas with x- and y-offset. It's strange that I didn't recieved any answers...
In details, I am looking for an example exactly like below image. I got a good example in this link https://github.com/woozzu/IndexableListView. Its works fine as my requirement.But problem when i implementing to my project it is showing error in list view. below is my code plz help me. i am new to this topic. Thank you in advance!
looking for:
here is my code below plz say my mistake..
MainActivity .java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener {
private ListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
EfficientAdapter2 objectAdapter1;
int textlength=0;
private CheckBox checkStat, checkRoutine, checkTat;
private GestureDetector mGestureDetector;
private ArrayList<CountriesList> elements;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan"," txtScanResult ");
//Arrays.sort(CountriesList.name);
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE", Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
objectAdapter = new EfficientAdapter(this, elements );
listView.setAdapter(objectAdapter);
Button refreshButton= (Button)findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
objectAdapter1 = new EfficientAdapter2(MainActivity.this);
// objectAdapter = new EfficientAdapter(MainActivity.this);// adapter with new data
listView.setAdapter(objectAdapter1);
Log.i("notifyDataSetChanged", "data updated");
objectAdapter1.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.java
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private AlphabetIndexer alphaIndexer;
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context, ArrayList<CountriesList> elements) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
public int getCount() {
return CountriesList.name.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.name);
holder.text2 = (TextView) convertView
.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView
.findViewById(R.id.date);
holder.text4 = (TextView) convertView
.findViewById(R.id.age);
holder.text5 = (TextView) convertView
.findViewById(R.id.gender);
holder.text6 = (TextView) convertView
.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView
.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView
.findViewById(R.id.bedno);
holder.btnList = (Button)convertView.findViewById(R.id.listbutton);
// holder.btnList.setOnClickListener(this);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(CountriesList.name[position]);
holder.text2.setText(CountriesList.mrn[position]);
holder.text3.setText(CountriesList.actualstart[position]);
holder.text4.setText(CountriesList.age[position]);
holder.text5.setText(CountriesList.gender[position]);
holder.text6.setText(CountriesList.wardNo[position]);
holder.text7.setText(CountriesList.roomNo[position]);
holder.text8.setText(CountriesList.bedNo[position]);
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(k)))
return j;
}
} else {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
IndexableListView.java
public class IndexableListView extends ListView {
private boolean mIsFastScrollEnabled = false;
private IndexScroller mScroller = null;
private GestureDetector mGestureDetector = null;
public IndexableListView(Context context) {
super(context);
}
public IndexableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IndexableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean isFastScrollEnabled() {
return mIsFastScrollEnabled;
}
#Override
public void setFastScrollEnabled(boolean enabled) {
mIsFastScrollEnabled = enabled;
if (mIsFastScrollEnabled) {
if (mScroller == null)
mScroller = new IndexScroller(getContext(), this);
} else {
if (mScroller != null) {
mScroller.hide();
mScroller = null;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Overlay index bar
if (mScroller != null)
mScroller.draw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Intercept ListView's touch event
if (mScroller != null && mScroller.onTouchEvent(ev))
return true;
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// If fling happens, index bar shows
mScroller.show();
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
mGestureDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mScroller != null)
mScroller.setAdapter(adapter);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mScroller != null)
mScroller.onSizeChanged(w, h, oldw, oldh);
}
}
StringMatcher.java
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
if (isKorean(value.charAt(i)) && isInitialSound(keyword.charAt(j))) {
} else {
if (keyword.charAt(j) == value.charAt(i)) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(char c) {
return false;
}
private static boolean isInitialSound(char c) {
return false;
}
}
IndexScroller.java
public class IndexScroller {
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 10 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity, indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
, (mListViewHeight - previewSize) / 2
, (mListViewWidth - previewSize) / 2 + previewSize
, (mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
, previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
, mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth
, mIndexbarMargin
, w - mIndexbarMargin
, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(3000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top + mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
}
if i add this it works code in mainactivity
listView = (ListView) findViewById(R.id.homelistView);
your are using a custom ListView class, com.woozzu.android.widget.IndexableListView
You have to replace your "ListView " in layout file to a "com.woozzu.android.widget.IndexableListView"
Change your Layout to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ff3344"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:layout_alignTop="#+id/scrollView1"
android:layout_toRightOf="#+id/scrollView1" >
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The solution Suggested by #Anis is the only working solution I found. In addition to that, If you want Click listeners to components on your List View Items, you have to update the Code as mentioned here, https://github.com/denley/IndexableListView/commit/18210a54487ba079bb332fafec709e2de26883db
This Activity Code move Like a Iphone Horizontal Scroll.
second Code is ScrollView Library.
The Better Idea If you have, Comment Please.
Or Critics Welcome.
public class HorizontalScrollActivity extends Activity {
private StickyHorizontalScrollView scrollView;
private ArrayList<View> viewList = new ArrayList<View>();
private ViewGroup mLayout;
private ViewGroup mLayout2;
private ViewGroup mLayout3;
private LinearLayout mLayoutContainer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scrollView = new StickyHorizontalScrollView(this);
scrollView.setHorizontalScrollBarEnabled(false);
scrollView.setFadingEdgeLength(0);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DisplayMetrics mDisplayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
int deviceWidth = mDisplayMetrics.widthPixels;
int deviceHeight = mDisplayMetrics.heightPixels;
mLayout = (ViewGroup)inflater.inflate(R.layout.main, null);
mLayout.setLayoutParams(new LayoutParams(deviceWidth, deviceHeight));
mLayout2 = (ViewGroup)inflater.inflate(R.layout.main2, null);
mLayout2.setLayoutParams(new LayoutParams(deviceWidth, deviceHeight));
mLayout3 = (ViewGroup)inflater.inflate(R.layout.main3, null);
mLayoutContainer = (LinearLayout)mLayout3.findViewById(R.id.bodyLayout);
mLayout3.removeView(mLayoutContainer);
viewList.add(mLayout);
viewList.add(mLayout2);
int i = 0;
for(View v : viewList){
mLayoutContainer.addView(v);
scrollView.addStickyPosition(i++ * deviceWidth);
}
scrollView.addView(mLayoutContainer);
setContentView(scrollView);
}
}
And This Code for Iphonish HorizontalScrollView Library.
Library Page
public class StickyHorizontalScrollView extends HorizontalScrollView {
protected ArrayList<Integer> stickyPositions = new ArrayList<Integer>();
private boolean flinged = false;
private final String TAG = "StickyHorizontalScrollView ==========";
public StickyHorizontalScrollView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
public void fling(int velocityX) {
// TODO Auto-generated method stub
Log.d(TAG, "FLING");
flinged = true;
int lastSmaller = 0;
for(int sticky : stickyPositions){
if(velocityX > 0 && sticky > getScrollX()){
smoothScrollTo(sticky, getScrollY());
break;
}else if(velocityX < 0){
if(sticky > getScrollX()){
smoothScrollTo(lastSmaller, getScrollY());
break;
}else{
lastSmaller = sticky;
}
}
}
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO Auto-generated method stub
Log.d(TAG, "TOUCH");
flinged = false;
boolean res = super.onTouchEvent(ev);
if(ev.getAction() == MotionEvent.ACTION_UP && !flinged){
sanitizeScrollPosition();
}
return res;
}
public void sanitizeScrollPosition(){
Log.d(TAG, "SANITIZE");
Integer minDistance = 0;
Integer minStickyPosition = 0;
for(int sticky : stickyPositions){
int distance = Math.abs(getScrollX() - sticky);
if(minDistance == null || minDistance > distance){
minStickyPosition = sticky;
minDistance = distance;
}
}
smoothScrollTo(minStickyPosition, getScrollY());
}
public void addStickyPosition(int x){
Log.d(TAG, "ADD STICKY POSITION");
stickyPositions.add(x);
Collections.sort(stickyPositions);
}
public void clearStickyPositions(){
Log.d(TAG, "CLEAR STICKY POSITION");
stickyPositions.clear();
}
}
I know you asked this question a year ago but for those who are still looking for that I found this amazing example and it made my day :
https://github.com/ysamlan/horizontalpager
hope you find it useful as well :)
When I am trying to fling example this error faced. with java Null pointer exception.
My java code
public class LearnCount extends Activity {
private FlingGallery mGallery;
public boolean onTouchEvent(MotionEvent event) {
return mGallery.onGalleryTouchEvent(event);
}
private String[] teststr = {
"test1","test2","test3","test4","test5"
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
LinearLayout productHolder = (LinearLayout) findViewById(R.id.linearLayoutOfCount);
mGallery = new FlingGallery(this);
mGallery.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, teststr) {
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println(mGallery.getCurrentPosition() + " position");
if (convertView != null
&& convertView instanceof GalleryViewItem) {
GalleryViewItem galleryView = (GalleryViewItem) convertView;
//galleryView.pImage.setImageResource(mImageIds[position]);
galleryView.b.setText(teststr[position]);
return galleryView;
}
GalleryViewItem gvi = new GalleryViewItem(getApplicationContext(), position);
gvi.b.setText(teststr[position]);
return gvi;
}
});
productHolder.addView(mGallery);
}
public class GalleryViewItem extends TableLayout {
private TextView b;
public GalleryViewItem(Context context, int position) {
super(context);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.test, null);
b = (TextView) v.findViewById(R.id.test);
this.addView(v);
}
}
public class FlingGallery extends FrameLayout {
// Constants
private final int swipe_min_distance = 120;
private final int swipe_max_off_path = 250;
private final int swipe_threshold_veloicty = 400;
// Properties
private int mViewPaddingWidth = 0;
private int mAnimationDuration = 250;
private float mSnapBorderRatio = 0.5f;
private boolean mIsGalleryCircular = false;
// Members
private int mGalleryWidth = 0;
private boolean mIsTouched = false;
private boolean mIsDragging = false;
private float mCurrentOffset = 0.0f;
private long mScrollTimestamp = 0;
private int mFlingDirection = 0;
public int mCurrentPosition = 0;
private int mCurrentViewNumber = 0;
private Context mContext;
private Adapter mAdapter;
private FlingGalleryView[] mViews;
private FlingGalleryAnimation mAnimation;
private GestureDetector mGestureDetector;
private Interpolator mDecelerateInterpolater;
public FlingGallery(Context context) {
super(context);
mContext = context;
mAdapter = null;
mViews = new FlingGalleryView[3];
mViews[0] = new FlingGalleryView(0, this);
mViews[1] = new FlingGalleryView(1, this);
mViews[2] = new FlingGalleryView(2, this);
mAnimation = new FlingGalleryAnimation();
mGestureDetector = new GestureDetector(new FlingGestureDetector());
mDecelerateInterpolater = AnimationUtils.loadInterpolator(mContext,
android.R.anim.decelerate_interpolator);
}
public void setPaddingWidth(int viewPaddingWidth) {
mViewPaddingWidth = viewPaddingWidth;
}
public void setAnimationDuration(int animationDuration) {
mAnimationDuration = animationDuration;
}
public void setSnapBorderRatio(float snapBorderRatio) {
mSnapBorderRatio = snapBorderRatio;
}
public int getCurrentPosition() {
return mCurrentPosition;
}
public void setIsGalleryCircular(boolean isGalleryCircular) {
if (mIsGalleryCircular != isGalleryCircular) {
mIsGalleryCircular = isGalleryCircular;
if (mCurrentPosition == getFirstPosition()) {
// We need to reload the view immediately to the left to
// change it to circular view or blank
mViews[getPrevViewNumber(mCurrentViewNumber)]
.recycleView(getPrevPosition(mCurrentPosition));
}
if (mCurrentPosition == getLastPosition()) {
// We need to reload the view immediately to the right to
// change it to circular view or blank
mViews[getNextViewNumber(mCurrentViewNumber)]
.recycleView(getNextPosition(mCurrentPosition));
}
}
}
public int getGalleryCount() {
return (mAdapter == null) ? 0 : mAdapter.getCount();
}
public int getFirstPosition() {
return 0;
}
public int getLastPosition() {
return (getGalleryCount() == 0) ? 0 : getGalleryCount() - 1;
}
private int getPrevPosition(int relativePosition) {
int prevPosition = relativePosition - 1;
if (prevPosition < getFirstPosition()) {
prevPosition = getFirstPosition() - 1;
if (mIsGalleryCircular == true) {
prevPosition = getLastPosition();
}
}
return prevPosition;
}
private int getNextPosition(int relativePosition) {
int nextPosition = relativePosition + 1;
if (nextPosition > getLastPosition()) {
nextPosition = getLastPosition() + 1;
if (mIsGalleryCircular == true) {
nextPosition = getFirstPosition();
}
}
return nextPosition;
}
private int getPrevViewNumber(int relativeViewNumber) {
return (relativeViewNumber == 0) ? 2 : relativeViewNumber - 1;
}
private int getNextViewNumber(int relativeViewNumber) {
return (relativeViewNumber == 2) ? 0 : relativeViewNumber + 1;
}
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
// Calculate our view width
mGalleryWidth = right - left;
if (changed == true) {
// Position views at correct starting offsets
mViews[0].setOffset(0, 0, mCurrentViewNumber);
mViews[1].setOffset(0, 0, mCurrentViewNumber);
mViews[2].setOffset(0, 0, mCurrentViewNumber);
}
}
public void setAdapter(Adapter adapter) {
mAdapter = adapter;
mCurrentPosition = 0;
mCurrentViewNumber = 0;
// Load the initial views from adapter
mViews[0].recycleView(mCurrentPosition);
mViews[1].recycleView(getNextPosition(mCurrentPosition));
mViews[2].recycleView(getPrevPosition(mCurrentPosition));
// Position views at correct starting offsets
mViews[0].setOffset(0, 0, mCurrentViewNumber);
mViews[1].setOffset(0, 0, mCurrentViewNumber);
mViews[2].setOffset(0, 0, mCurrentViewNumber);
}
private int getViewOffset(int viewNumber, int relativeViewNumber) {
// Determine width including configured padding width
int offsetWidth = mGalleryWidth + mViewPaddingWidth;
// Position the previous view one measured width to left
if (viewNumber == getPrevViewNumber(relativeViewNumber)) {
return offsetWidth;
}
// Position the next view one measured width to the right
if (viewNumber == getNextViewNumber(relativeViewNumber)) {
return offsetWidth * -1;
}
return 0;
}
void movePrevious() {
// Slide to previous view
mFlingDirection = 1;
processGesture();
}
void moveNext() {
// Slide to next view
mFlingDirection = -1;
processGesture();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
movePrevious();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
moveNext();
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
}
return super.onKeyDown(keyCode, event);
}
public boolean onGalleryTouchEvent(MotionEvent event) {
boolean consumed = mGestureDetector.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mIsTouched || mIsDragging) {
processScrollSnap();
processGesture();
}
}
return consumed;
}
void processGesture() {
int newViewNumber = mCurrentViewNumber;
int reloadViewNumber = 0;
int reloadPosition = 0;
mIsTouched = false;
mIsDragging = false;
if (mFlingDirection > 0) {
if (mCurrentPosition > getFirstPosition()
|| mIsGalleryCircular == true) {
// Determine previous view and outgoing view to recycle
newViewNumber = getPrevViewNumber(mCurrentViewNumber);
mCurrentPosition = getPrevPosition(mCurrentPosition);
reloadViewNumber = getNextViewNumber(mCurrentViewNumber);
reloadPosition = getPrevPosition(mCurrentPosition);
}
}
if (mFlingDirection < 0) {
if (mCurrentPosition < getLastPosition()
|| mIsGalleryCircular == true) {
// Determine the next view and outgoing view to recycle
newViewNumber = getNextViewNumber(mCurrentViewNumber);
mCurrentPosition = getNextPosition(mCurrentPosition);
reloadViewNumber = getPrevViewNumber(mCurrentViewNumber);
reloadPosition = getNextPosition(mCurrentPosition);
}
}
if (newViewNumber != mCurrentViewNumber) {
mCurrentViewNumber = newViewNumber;
// Reload outgoing view from adapter in new position
mViews[reloadViewNumber].recycleView(reloadPosition);
}
// Ensure input focus on the current view
mViews[mCurrentViewNumber].requestFocus();
// Run the slide animations for view transitions
mAnimation.prepareAnimation(mCurrentViewNumber);
this.startAnimation(mAnimation);
// Reset fling state
mFlingDirection = 0;
//checkNextBackButton(mCurrentPosition);
System.out.println("positionFiling" + mCurrentPosition);
}
void processScrollSnap() {
// Snap to next view if scrolled passed snap position
float rollEdgeWidth = mGalleryWidth * mSnapBorderRatio;
int rollOffset = mGalleryWidth - (int) rollEdgeWidth;
int currentOffset = mViews[mCurrentViewNumber].getCurrentOffset();
if (currentOffset <= rollOffset * -1) {
// Snap to previous view
mFlingDirection = 1;
}
if (currentOffset >= rollOffset) {
// Snap to next view
mFlingDirection = -1;
}
}
public class FlingGalleryView {
private int mViewNumber;
private FrameLayout mParentLayout;
private FrameLayout mInvalidLayout = null;
private LinearLayout mInternalLayout = null;
private View mExternalView = null;
public FlingGalleryView(int viewNumber, FrameLayout parentLayout) {
mViewNumber = viewNumber;
mParentLayout = parentLayout;
// Invalid layout is used when outside gallery
mInvalidLayout = new FrameLayout(mContext);
mInvalidLayout.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
// Internal layout is permanent for duration
mInternalLayout = new LinearLayout(mContext);
mInternalLayout.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mParentLayout.addView(mInternalLayout);
}
public void recycleView(int newPosition) {
if (mExternalView != null) {
mInternalLayout.removeView(mExternalView);
}
if (mAdapter != null) {
if (newPosition >= getFirstPosition()
&& newPosition <= getLastPosition()) {
mExternalView = mAdapter.getView(newPosition,
mExternalView, mInternalLayout);
} else {
mExternalView = mInvalidLayout;
}
}
if (mExternalView != null) {
mInternalLayout.addView(mExternalView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
}
}
public void setOffset(int xOffset, int yOffset,
int relativeViewNumber) {
// Scroll the target view relative to its own position relative
// to currently displayed view
mInternalLayout.scrollTo(getViewOffset(mViewNumber,
relativeViewNumber)
+ xOffset, yOffset);
}
public int getCurrentOffset() {
// Return the current scroll position
return mInternalLayout.getScrollX();
}
public void requestFocus() {
mInternalLayout.requestFocus();
}
}
public class FlingGalleryAnimation extends Animation {
private boolean mIsAnimationInProgres;
private int mRelativeViewNumber;
private int mInitialOffset;
private int mTargetOffset;
private int mTargetDistance;
public FlingGalleryAnimation() {
mIsAnimationInProgres = false;
mRelativeViewNumber = 0;
mInitialOffset = 0;
mTargetOffset = 0;
mTargetDistance = 0;
}
public void prepareAnimation(int relativeViewNumber) {
// If we are animating relative to a new view
if (mRelativeViewNumber != relativeViewNumber) {
if (mIsAnimationInProgres == true) {
// We only have three views so if requested again to
// animate in same direction we must snap
int newDirection = (relativeViewNumber == getPrevViewNumber(mRelativeViewNumber)) ? 1
: -1;
int animDirection = (mTargetDistance < 0) ? 1 : -1;
// If animation in same direction
if (animDirection == newDirection) {
// Ran out of time to animate so snap to the target
// offset
mViews[0].setOffset(mTargetOffset, 0,
mRelativeViewNumber);
mViews[1].setOffset(mTargetOffset, 0,
mRelativeViewNumber);
mViews[2].setOffset(mTargetOffset, 0,
mRelativeViewNumber);
}
}
// Set relative view number for animation
mRelativeViewNumber = relativeViewNumber;
}
// Note: In this implementation the targetOffset will always be
// zero
// as we are centering the view; but we include the calculations
// of
// targetOffset and targetDistance for use in future
// implementations
mInitialOffset = mViews[mRelativeViewNumber].getCurrentOffset();
mTargetOffset = getViewOffset(mRelativeViewNumber,
mRelativeViewNumber);
mTargetDistance = mTargetOffset - mInitialOffset;
// Configure base animation properties
this.setDuration(mAnimationDuration);
this.setInterpolator(mDecelerateInterpolater);
// Start/continued animation
mIsAnimationInProgres = true;
}
protected void applyTransformation(float interpolatedTime,
Transformation transformation) {
// Ensure interpolatedTime does not over-shoot then calculate
// new offset
interpolatedTime = (interpolatedTime > 1.0f) ? 1.0f
: interpolatedTime;
int offset = mInitialOffset
+ (int) (mTargetDistance * interpolatedTime);
for (int viewNumber = 0; viewNumber < 3; viewNumber++) {
// Only need to animate the visible views as the other view
// will always be off-screen
if ((mTargetDistance > 0 && viewNumber != getNextViewNumber(mRelativeViewNumber))
|| (mTargetDistance < 0 && viewNumber != getPrevViewNumber(mRelativeViewNumber))) {
mViews[viewNumber].setOffset(offset, 0,
mRelativeViewNumber);
}
}
}
public boolean getTransformation(long currentTime,
Transformation outTransformation) {
if (super.getTransformation(currentTime, outTransformation) == false) {
// Perform final adjustment to offsets to cleanup animation
mViews[0].setOffset(mTargetOffset, 0, mRelativeViewNumber);
mViews[1].setOffset(mTargetOffset, 0, mRelativeViewNumber);
mViews[2].setOffset(mTargetOffset, 0, mRelativeViewNumber);
// Reached the animation target
mIsAnimationInProgres = false;
return false;
}
// Cancel if the screen touched
if (mIsTouched || mIsDragging) {
// Note that at this point we still consider ourselves to be
// animating
// because we have not yet reached the target offset; its
// just that the
// user has temporarily interrupted the animation with a
// touch gesture
return false;
}
return true;
}
}
private class FlingGestureDetector extends GestureDetector.SimpleOnGestureListener {
public boolean onDown(MotionEvent e) {
// Stop animation
mIsTouched = true;
// Reset fling state
mFlingDirection = 0;
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (e2.getAction() == MotionEvent.ACTION_MOVE) {
if (mIsDragging == false) {
// Stop animation
mIsTouched = true;
// Reconfigure scroll
mIsDragging = true;
mFlingDirection = 0;
mScrollTimestamp = System.currentTimeMillis();
mCurrentOffset = mViews[mCurrentViewNumber]
.getCurrentOffset();
}
float maxVelocity = mGalleryWidth
/ (mAnimationDuration / 1000.0f);
long timestampDelta = System.currentTimeMillis()
- mScrollTimestamp;
float maxScrollDelta = maxVelocity
* (timestampDelta / 1000.0f);
float currentScrollDelta = e1.getX() - e2.getX();
if (currentScrollDelta < maxScrollDelta * -1)
currentScrollDelta = maxScrollDelta * -1;
if (currentScrollDelta > maxScrollDelta)
currentScrollDelta = maxScrollDelta;
int scrollOffset = Math.round(mCurrentOffset
+ currentScrollDelta);
// We can't scroll more than the width of our own frame
// layout
if (scrollOffset >= mGalleryWidth)
scrollOffset = mGalleryWidth;
if (scrollOffset <= mGalleryWidth * -1)
scrollOffset = mGalleryWidth * -1;
mViews[0].setOffset(scrollOffset, 0, mCurrentViewNumber);
mViews[1].setOffset(scrollOffset, 0, mCurrentViewNumber);
mViews[2].setOffset(scrollOffset, 0, mCurrentViewNumber);
}
return false;
}
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) <= swipe_max_off_path) {
if (e2.getX() - e1.getX() > swipe_min_distance
&& Math.abs(velocityX) > swipe_threshold_veloicty) {
movePrevious();
}
if (e1.getX() - e2.getX() > swipe_min_distance
&& Math.abs(velocityX) > swipe_threshold_veloicty) {
moveNext();
}
}
return false;
}
public void onLongPress(MotionEvent e) {
// Finalise scrolling
mFlingDirection = 0;
processGesture();
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
// Reset fling state
mFlingDirection = 0;
return false;
}
}
}
}
My log cat error message is:
I am the beginner for android, something wrong my code?
LinearLayout productHolder = (LinearLayout) findViewById(R.id.linearLayoutOfCount);
Is returning null. Make sure you are referencing the correct id.