2017-04-20 25 views
0

我有一個包含6 * 8 ImageViews的GridView。我現在想要能夠拖動1個ImageView並將它的位置與另一個ImageView交換。 我嘗試了不適合我的不同OnDrag方法。我現在用onTouch-Method進行了測試,但是它沒有按照計劃工作。Android拖放Imageview(這是GridView的一部分)

你們其中一人已經有這個問題,或者可以告訴我如何實施它?

public class GameActivity extends AppCompatActivity implements View.OnTouchListener{ 
private RelativeLayout rootLayout; 
private GridLayout gl_gamefield; 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game); 
rootLayout = (RelativeLayout) findViewById(R.id.rootLayout); 
createGameField(6,8); // columns, rows 
} 

public void createGameField(int columns, int rows){ 
    gl_gamefield = new GridLayout(this); 
    RelativeLayout.LayoutParams paramsGameField = new RelativeLayout.LayoutParams(getScreenSize()[0],(int)(getScreenSize()[1]-gameFieldFactor)); 
    paramsGameField.addRule(RelativeLayout.ABOVE, R.id.ad_view); 
    paramsGameField.setMargins(0,0,0,20); 
    gl_gamefield.setLayoutParams(paramsGameField); 
    gl_gamefield.setRowCount(rows); 
    gl_gamefield.setColumnCount(columns); 
    rootLayout.addView(gl_gamefield); 

    ImageView[][] fields = new ImageView[columns][rows]; 
    LinearLayout.LayoutParams layoutFields =new LinearLayout.LayoutParams((int)(getScreenSize()[0]/columns),(int)((getScreenSize()[1]-gameFieldFactor)/rows)); 
    int[][] colorFields = new int[columns][rows]; 

    for(int y = 0; y < rows; y++){ 
     for(int x = 0; x < columns; x++){ 
      fields[x][y] = new ImageView(this); 
      fields[x][y].setLayoutParams(layoutFields); 
      fields[x][y].setBackgroundColor(Color.rgb(30*x,20*y,10*(x+y))); 
      fields[x][y].setTag(x +""+ y); 
      fields[x][y].setOnTouchListener(this); 
      gl_gamefield.addView(fields[x][y]); 
     } 
    } 
} 

public int[] getScreenSize(){ 
    Display display = getWindowManager().getDefaultDisplay(); 
    Point size = new Point(); 
    display.getSize(size); 
    int width = size.x; 
    int height = size.y; 

    int[] screenSize = {width, height}; 

    return screenSize; 
} 

public boolean onTouch(final View v, final MotionEvent event) { 

    switch(event.getAction()){ 
     case MotionEvent.ACTION_DOWN: 

      if(cdt_running) cdt.cancel(); 

      cdt_running=true; 
      cdt = new CountDownTimer(30000, 20) { 

       public void onTick(long millis) { 
        x=event.getRawX()-(v.getWidth()/2); 
        y=event.getRawY()-(v.getHeight()/2); 
        v.setX(x); 
        v.setY(y); 

       } 
       public void onFinish() { 
        cdt_running=false; 
       } 
      }.start(); 


      //ToastMsg("Action_down"); 
      break; 
     case MotionEvent.ACTION_UP: 
      ToastMsg("Action_up"); 
      break; 

    } 

    return false; 
} 

這是我最後的onTouch方法。但它並沒有像我想要的那樣安靜工作。

如果有人可以幫助我,即使這可能是一個愚蠢的問題,因爲我真的沒有使用android開發經驗會很高興。

回答