Search code examples
javaimagemove

Move image in Android


In google I coulnd't search anything, only moving animation. I want to move my "imgview" object. 5 pixels by 1 button click. (I want to make a game. Every click button (arrow) hero walks 5 pixels up screen) I think that this will be simple code. I have relativelayout.

     button1.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {

            //// something like hero._y = hero._y - 5

        }
        });

What code I must use?


Solution

  •   button1.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
    
                 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                             moveRight = settings.getInt("rightValue", moveRight) +5;
                            //---------------- moving imageview  ----------------------------------
                            RelativeLayout.LayoutParams params = (LayoutParams) alert.getLayoutParams();
                             params.setMargins(moveRight, 0, 0, 0);
                            alert.setLayoutParams(params);
    
    
    
        }       
    

    ok so this is how I did it, first I make an int for the directions you want to move I called mine moveRight, then make a SharedPreferences so your ImageView location will be saved each time you move it, make sure where you call "moveRight = settings.getInt("rightValue", moveRight) +5;" you don't forget to put how far you want to move the ImageView by adding either +5 (for moving right) or -5 (for moving left) like I already did there, the code after that is what you will need to actually move the ImageView, and the line that has "params.setMargins(moveRight, 0, 0, 0);" the next int after moveRight will move the ImageView up or down. you could probably copy and past this and it will work just fine as long as you import all the right stuff and you got all your buttons and int's declared

    hope I was clear I'm not the best at english skills or giving understandable help LOL