2017-04-19 28 views
0

我試圖將已經繪製到屏幕的位圖轉換爲imageView,以便我可以啓用對其的拖動方法& ..這是唯一的方法我想我可以實現這一點。將位圖轉換爲imageview以使用ontouchlistener進行拖放

I嘗試將加載的位圖(hazardCard)加載到名爲cardImage1的imageview中。

代碼:

public class PlayScreen extends GameScreen { 


    // ///////////////////////////////////////////////////////////////////////// 
    // Properties 
    // ///////////////////////////////////////////////////////////////////////// 
    private Rect backButtonBound; 
    private Rect hazardCardBound; 

    private Music screenClickMusic; 


    /** 
    * Width and height of the level 
    */ 
    // private final float LEVEL_WIDTH = 1000.0f; 
    //private final float LEVEL_HEIGHT = 1000.0f; 

    /** 
    * Define viewports for this layer and the associated screen projection 
    */ 
    private ScreenViewport mScreenViewport; 
    private LayerViewport mLayerViewport; 

    private Bitmap backgroundBitmap; 
    private Bitmap backButton; 
    private Bitmap PlayScreenTitle; 
    private Bitmap hazardCard; 
    private Rect frontLayerBound; 
    private Rect playScreenTitleBound; 

    private ImageView cardImage1; 
    private ViewGroup rootLayout; 
    private int _xDelta; 
    private int _yDelta; 
    public View view; 

    /** 
    * User input controls for managing the player and the game 
    */ 
    // protected InputControl pauseButton 

    // ///////////////////////////////////////////////////////////////////////// 
    // Constructors 
    // ///////////////////////////////////////////////////////////////////////// 

    /** 
    * Create a game 
    * 
    * @param game 
    *   Game to which this screen belongs */ 

    public PlayScreen(Game game) { 
     super("PlayScreen", game); 

     //Define the rects what will be used to 'hold' the images 
     int spacingX = game.getScreenWidth()/8; 
     int spacingY = game.getScreenHeight()/8; 
     int padding = spacingY/10; //padding between each button 
     int line = 1; //each button is on a new 'line' (under each other) 


     // Load in the assets used by the demo 
     AssetStore assetManager = game.getAssetManager(); 
     assetManager.loadAndAddBitmap("pitch", "img/pitch.png"); 
     assetManager.loadAndAddBitmap("backButton", "img/back_button.png"); 
     assetManager.loadAndAddBitmap("hazardCard", "img/hazard_card.jpg"); 


     // Define Rectangles for Bitmaps 
     // playScreenTitleBound = new Rect(spacingX * 2, spacingY * 0, spacingX * 6, spacingY * 1); 

     this.backgroundBitmap = assetManager.getBitmap("pitch"); 
     this.backButton = assetManager.getBitmap("backButton"); 
     this.hazardCard = assetManager.getBitmap("hazardCard"); 

     //load in sounds 
     assetManager.loadAndAddMusic("screenClickMusic", "music/buttonPress.mp3"); 

     //initialise 
     this.screenClickMusic = assetManager.getMusic("screenClickMusic"); 

    } 

    // ///////////////////////////////////////////////////////////////////////// 
    // Support methods 
    // ///////////////////////////////////////////////////////////////////////// 

    // ///////////////////////////////////////////////////////////////////////// 
    // Update and Draw methods 
    // ///////////////////////////////////////////////////////////////////////// 

    @Override 
    public void update(ElapsedTime elapsedTime) { 

     //process any touch events occurring since the update 
     Input input = game.getInput(); 
     List<TouchEvent> touchEvents = input.getTouchEvents(); 

     if (touchEvents.size() > 0) { 

      //Just check the first touch event that occurred in the frame. 
      //It means pressing the screen with several fingers may not 
      //trigger a 'button'. 
      TouchEvent touchEvent = touchEvents.get(0); 
      if (backButtonBound.contains((int) touchEvent.x, (int) touchEvent.y) 
        && touchEvent.type == TouchEvent.TOUCH_UP) { 
       // If the play game area has been touched then swap screens 
       game.getScreenManager().removeScreen(this.getName()); 
       MenuScreen menuScreen = new MenuScreen(game); 
       if (Settings.soundEnabled) { 
        screenClickMusic.play(); 
       } 
       // As it's the only added screen it will become active. 
       game.getScreenManager().addScreen(menuScreen); 
      } /*else if (hazardCardBound.contains((int) touchEvent.x, (int) touchEvent.y) 
        && touchEvent.type == TouchEvent.TOUCH_DOWN) { 
       RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 
       _xDelta = X - lparams.leftMargin; 
       _yDelta = Y - lparams.topMargin; 

      }*/ 
     } 
    } 
    @Override 
    public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) { 
    // load hazard playing card 
     /*ImageView hazardCardImageView = (ImageView) view.findViewById(R.id.hazardCardImageView); 
     if (hazardCard != null) { 
      hazardCardImageView.setImageBitmap(hazardCard); 
     } 

     cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView); 
     RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150); 
     cardImage1.setLayoutParams(layoutParams); 
     cardImage1.setOnTouchListener(new ChoiceTouchListener());*/ 

     // Get and draw the bitmaps into the defined rectangles 
     Bitmap backButton = game.getAssetManager().getBitmap("backButton"); 

     // Create the screen to black and define a clip based on the viewport 
     graphics2D.clear(Color.BLACK); 
     //graphics2D.clipRect(mScreenViewport.toRect()); 
     // Define the rects what will be used to 'hold' the images 
     int spacingX = game.getScreenWidth()/8; 
     int spacingY = game.getScreenHeight()/8; 
     int padding = spacingY/10; //padding between each button 
     int line = 1; //each button is on a new 'line' (under each other) 

     hazardCardBound = new Rect(spacingX, spacingY * 2 + padding, spacingX * 7, spacingY * 3); 

     if (frontLayerBound == null) { 
      frontLayerBound = new Rect(0, 0, graphics2D.getSurfaceWidth(), 
        graphics2D.getSurfaceHeight()); 
     } 

     if (backButtonBound == null) { 
      int left = 10; 
      int bottom = (graphics2D.getSurfaceHeight() - 120); 

      backButtonBound = new Rect(left, bottom, left + 100, bottom + 120); 
     } 

//代碼加入 cardImage1 =(ImageView的)rootLayout.findViewById(R.id.hazardCardImageView);

 cardImage1.setLayoutParams(layoutParams); 
     cardImage1.setOnTouchListener(new ChoiceTouchListener()); 
     cardImage1.setOnTouchListener(new ChoiceTouchListener()); 
     cardImage1.setImageBitmap(hazardCard);*/ 

     //draw bitmaps with relative bounds 
     graphics2D.drawBitmap(backgroundBitmap, null, frontLayerBound,null); 
     graphics2D.drawBitmap(backButton, null, backButtonBound, null); 
     graphics2D.drawBitmap(hazardCard,null, hazardCardBound, null); 


     RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(500, 150); 
     cardImage1.setLayoutParams(layoutParams); 
     cardImage1.setImageBitmap(hazardCard); 
     cardImage1.setOnTouchListener(new ChoiceTouchListener()); 

    } 

    private final class ChoiceTouchListener implements View.OnTouchListener { 
     public boolean onTouch(View view, MotionEvent event) { 
      final int X = (int) event.getRawX(); 
      final int Y = (int) event.getRawY(); 
      switch (event.getAction() & MotionEvent.ACTION_MASK) { 
       case MotionEvent.ACTION_DOWN: 
        RelativeLayout.LayoutParams lparams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 
        _xDelta = X - lparams.leftMargin; 
        _yDelta = Y - lparams.topMargin; 
        break; 
       case MotionEvent.ACTION_UP: 
        break; 
       case MotionEvent.ACTION_POINTER_DOWN: 
        break; 
       case MotionEvent.ACTION_POINTER_UP: 
        break; 
       case MotionEvent.ACTION_MOVE: 
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 
        layoutParams.leftMargin = X - _xDelta; 
        layoutParams.topMargin = Y - _yDelta; 
        layoutParams.rightMargin = 0b11111111111111111111111100000110; 
        layoutParams.bottomMargin = 0b11111111111111111111111100000110; 
        view.setLayoutParams(layoutParams); 
        break; 
      } 
      rootLayout.invalidate(); 
      return true; 
     } 
    } 

編輯注:我在這行代碼添加到初始化的ImageView ..

編輯:主要業務類別:

import android.app.Activity; 
import android.app.FragmentManager; 
import android.graphics.PointF; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.ScaleGestureDetector; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.Window; 
import android.view.WindowManager; 

import com.example.llave_000.shootout.world.DemoGame; 
import android.view.GestureDetector; 
import android.widget.ImageView; 

public class MainActivity extends Activity implements View.OnTouchListener { 

    private float mScaleFactor = 1.0f; 
    private float mRotationDegrees = 0.f; 
    private float mFocusX = 0.f; 
    private float mFocusY = 0.f; 
    private ImageView cardImage1; 
    private ViewGroup rootLayout; 



    /** 
    * Game fragment instance 
    */ 
    private Game mGame; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 


     cardImage1 = (ImageView) rootLayout.findViewById(R.id.hazardCardImageView); 

     // Setup Gesture Detectors 
     mScaleDetector = new ScaleGestureDetector(getApplicationContext(), new ScaleListener()); 
     /*mRotateDetector = new RotationGestureDetector(getApplicationContext(), new RotateListener()); 
     mMoveDetector = new MoveGestureDetector(getApplicationContext(), new MoveListener());*/ 


     // Setup the window as suitable for a game, namely: full screen 
     // with no title and a request to keep the screen on. The changes 
     // are made before any content is inflated. 
     Window window = getWindow(); 
     window.requestFeature(Window.FEATURE_NO_TITLE); 
     window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 

     // Set the content view to use a simple frame layout 
     setContentView(R.layout.activity_main); 

     // Add in the main game fragment.. 
     FragmentManager fm = getFragmentManager(); 
     // MenuScreen menuScreen = (MenuScreen)fm.findFragmentById(R.id.activity_main_id); 
     mGame = (Game)fm.findFragmentById(R.id.activity_main_id); 

     if (mGame == null) { 
      mGame = new DemoGame(); //not sure if correct 
      fm.beginTransaction().add(R.id.activity_main_id, mGame) 
        .commit(); 
     } 


    } 



    @Override 
    public void onBackPressed() { 
     // If the fragment does not consume the back event then 
     // trigger the default behaviour 
     if(!mGame.onBackPressed()) 
      super.onBackPressed(); 
    } 

    /* public boolean onTouchEvent(MotionEvent me) { 
     if (me.getAction() == MotionEvent.ACTION_DOWN) { 
      //code in here to take me to new screen with match attax background 
      //with new screen displaying a card. then work on being able to move that card. 

      //playButtonY -= 20; 

     }*/ 
     // playButton.setY(playButtonY); 
     //code in here to take me to new screen with match attax background 
     //with new screen displaying a card. then work on being able to move that card. 

     //return true; 
    } 

新的錯誤:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.llave_000.shootout/com.example.llave_000.shootout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference 
    at com.example.llave_000.shootout.MainActivity.onCreate(MainActivity.java:42) 
    at android.app.Activity.performCreate(Activity.java:6662) 

編輯:: GameScreen分類:

import com.example.llave_000.shootout.Game; 
import com.example.llave_000.shootout.engine.ElapsedTime; 
import com.example.llave_000.shootout.engine.graphics.IGraphics2D; 
import com.example.llave_000.shootout.util.ILifeCycle; 

/** 
* GameScreen - represents a type of Screen in the Game. 
* methods 
* 
*/ 
public abstract class GameScreen { 

    /** 
    * Name that is given to this game screen 
    */ 
    protected final String name; 

    /** 
    * Return the name of this game screen 
    * 
    * @return Name of this game screen 
    */ 
    public String getName() { 
     return name; 
    } 

    /** 
    * Game to which game screen belongs 
    */ 
    protected final Game game; 

    /** 
    * Return the game to which this game screen is attached 
    * 
    * @return Game to which screen is attached 
    */ 
    public Game getGame() { 
     return game; 
    } 

    /** 
    * Create a new game screen associated with the specified game instance 
    * 
    * @param game 
    *   Game instance to which the game screen belongs 
    */ 
    public GameScreen(String name, Game game) { 
     this.name = name; 
     this.game = game; 
    } 

    /** 
    * Update the game screen. Invoked automatically from the game. 
    * 
    * NOTE: If the update is multi-threaded control should not be returned from 
    * the update call until all update processes have completed. 
    * 
    * @param elapsedTime 
    *   Elapsed time information for the frame 
    */ 
    public abstract void update(ElapsedTime elapsedTime); 

    /** 
    * Draw the game screen. Invoked automatically from the game. 
    * 
    * @param elapsedTime 
    *   Elapsed time information for the frame 
    * @param graphics2D 
    *   Graphics instance used to draw the screen 
    */ 
    public abstract void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D); 

    /** 
    * Invoked automatically by the game whenever the app is paused. 
    */ 
    public void pause() { 
    } 
    /** 
    * Invoked automatically by the game whenever the app is resumed. 
    */ 
    public void resume() { 
    } 

    /** 
    * Invoked automatically by the game whenever the app is disposed. 
    */ 
    public void dispose() { 
    } 
} 
+4

可能重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -it) – QBrute

回答

0

您的cardImage1未初始化。您正在設置null imageview上的佈局參數。這就是爲什麼它變得NullPointerException。 如果它解決了你的問題,那麼它很好,否則更新你的問題和錯誤日誌。

+0

我添加了一行代碼來初始化它。但不知道它是否合適..我如何將imageView初始化爲已加載的位圖? – Liam

+0

您的詳細信息不完整, 1.什麼是GameScreen小部件或活動或片段? (我想一個小部件,因爲我不能看到OnCreate()方法) 2.如果它是一個小部件,那麼你不能在那裏初始化'cardview1',因爲它可以在活動或片段中完成,這就是爲什麼你要說的錯誤。 –

+0

我把這行代碼: cardImage1 =(ImageView)rootLayout.findViewById(R.id.hazardCardImageView); 進入我的MainActivity類,在onCreate方法。 現在錯誤:java.lang.RuntimeException:無法啓動活動ComponentInfo {com.example.llave_000.shootout/com.example.llave_000.shootout.MainActivity}:java.lang.NullPointerException:嘗試調用虛擬方法'android。 view.View android.view.View.findViewById(int)'null對象引用 引發:java.lang.NullPointerException: at com.example.llave_000.shootout.MainActivity.onCreate(MainActivity.java:42) – Liam