2012-04-16 7 views
1

Android에 매우 익숙하며 잠시 동안 조사했지만 아직 답을 찾을 수 없습니다. 나는 간단한 해결책이 있다고 확신한다.view.getLocationOnScreen을 사용하는 NullPointerException

나는에 연결되어있는 NullPointException 받고 있어요 내 View characterContainer = findViewById(R.id.icon_container);

내가 알고있는 것처럼, 내가 onCreate() 방법을 구현하기 위해 노력하고 같은 레이아웃이 완전히 준비가 아니므로 아직 characterContainer = null 원인이있어 보인다 .

그래서 onStart() 또는 onResume()에 사용해야합니다.하지만 고민 중입니다. 이건 내 코드는 지금까지 있습니다 :

package harvest.life.game; 

import android.app.Activity; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.RelativeLayout; 

public class HarvestLifeActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     //find buttons on screen 
     Button up = (Button)findViewById(R.id.up); 
     up.setOnTouchListener(new UpListener()); 
     Button down = (Button)findViewById(R.id.down); 
     down.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons 
     Button left = (Button)findViewById(R.id.left); 
     left.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons 
     Button right = (Button)findViewById(R.id.right); 
     right.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons 
    } 
    //what up button does 
    private final class UpListener implements OnTouchListener { 
     public boolean onTouch(View v, MotionEvent event) { 

      switch (event.getAction()) { 
       case MotionEvent.ACTION_DOWN: 
        //as long as up button is pressed it will keep moving character up 
        while (event.getAction() == MotionEvent.ACTION_DOWN) 
        { 
         View characterContainer = findViewById(R.id.icon_container); 
         Drawable walking = getResources().getDrawable(R.drawable.test_circle_red); 
         int startX = characterContainer.getLeft(); 
         int startY = characterContainer.getTop(); 
         int defaultWidth = characterContainer.getWidth(); 
         int defaultHeight = characterContainer.getHeight(); 

         //create new position for character 1 pixel closer to the top of screen 
         int newX = startX - 1; 
         int newY = startY; 

         //remove character 
         RelativeLayout view = (RelativeLayout) characterContainer; 
         ViewGroup owner = (ViewGroup) view.getParent(); 
         owner.removeView(view); 

         //re make character in new position created above and assign background as walking forwards animation 
         RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight); 
         characParams.leftMargin = newY; 
         characParams.topMargin = newX; 
         characterContainer.setLayoutParams(characParams);   
         characterContainer.setBackgroundDrawable(walking); 
        } 
        break; 

        // when button is let go of 
       case MotionEvent.ACTION_UP: 
        RelativeLayout characterContainer = (RelativeLayout) 
        findViewById(R.id.icon_container); 
        Drawable standing = 
         getResources().getDrawable(R.drawable.test_circle); 
        //assign background back to standing animation 
        characterContainer.setBackgroundDrawable(standing); 
       default: 
        break; 
      } 
      return true; 
     } 
    } 
    public void onResume() { // what goes here? 

    } 
} 

내가 onResume 섹션에서 함수 호출의 종류를 둘 필요가 또는 내가 OnTouchListener 여기에 무엇을위한 코드를 삽입해야합니까?

은 여기 내 주 : 당신의 '최대'당신이 볼 수 있듯이

package harvest.life.game; 
import android.app.Activity; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.RelativeLayout; 

public class HarvestLifeActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     //find buttons on screen 
     Button up = (Button)findViewById(R.id.up); 
     //up.setOnTouchListener(new UpListener()); 
     Button down = (Button)findViewById(R.id.up); 
     //down.setOnTouchListener(new UpListener()); 
     Button left = (Button)findViewById(R.id.up); 
     //left.setOnTouchListener(new UpListener()); 
     Button right = (Button)findViewById(R.id.up); 
     //right.setOnTouchListener(new UpListener()); 
    } 

    public void onDownButtonClick(View view){ 
     while (event.getAction() == MotionEvent.ACTION_DOWN) 
     { 

      View characterContainer = findViewById(R.id.icon_container); 
      Drawable walking = getResources().getDrawable(R.drawable.test_circle_red); 
      int startX = characterContainer.getLeft(); 
      int startY = characterContainer.getTop(); 
      int defaultWidth = characterContainer.getWidth(); 
      int defaultHeight = characterContainer.getHeight(); 

       //create new position for character 1 pixel closer to the top of screen 
       int newX = startX - 1; 
       int newY = startY; 

       //remove character 
       RelativeLayout view = (RelativeLayout) characterContainer; 
       ViewGroup owner = (ViewGroup) view.getParent(); 
       owner.removeView(view); 

       //re make character in new position created above and assign background as walking forwards animation 
       RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight); 
       characParams.leftMargin = newY; 
       characParams.topMargin = newX; 
       characterContainer.setLayoutParams(characParams);   
       characterContainer.setBackgroundDrawable(walking); 
       } 
    } 

    public void onUpButtonClicked(View view){ 
     RelativeLayout characterContainer = (RelativeLayout) 
       findViewById(R.id.icon_container); 
     Drawable standing = 
       getResources().getDrawable(R.drawable.test_circle); 
     //assign background back to standing animation 
     characterContainer.setBackgroundDrawable(standing); 
    } 

    } 

, 나는 함수에 '아래로'코드를 넣어 :

여기
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/game_container" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="horizontal" 
android:background="#FFFFFF"> 

<RelativeLayout 
    android:id="@+id/side_bar_right" 
    android:layout_width="50dp" 
    android:layout_height="fill_parent" 
    android:layout_alignParentRight="true" 
    android:layout_alignParentTop="true" 
    android:background="#000000"> 

    <ImageView 
     android:contentDescription="@string/movement_button" 
     android:id="@+id/up" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_gravity="top" 
     android:src="@drawable/up" /> 

    <ImageView 
     android:contentDescription="@string/movement_button" 
     android:id="@+id/down" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:src="@drawable/down" /> 

    <ImageView 
     android:contentDescription="@string/movement_button" 
     android:id="@+id/right" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_alignParentLeft="true" 
     android:layout_centerVertical="true" 
     android:src="@drawable/right" /> 

</RelativeLayout> 

<RelativeLayout 
    android:id="@+id/side_bar_left" 
    android:layout_width="50dp" 
    android:layout_height="fill_parent" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:background="#000000"> 

    <ImageView 
     android:contentDescription="@string/movement_button" 
     android:id="@+id/left" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:layout_alignParentLeft="true" 
     android:layout_centerVertical="true" 
     android:src="@drawable/left" />  

</RelativeLayout> 

<RelativeLayout 
    android:id="@+id/icon_container" 
    android:layout_width="50dp" 
    android:layout_height="50dp" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:background="@drawable/test_circle" > 

</RelativeLayout > 

</RelativeLayout> 
+0

onResume()에서 코드를 사용하려면 다음과 같이하면됩니다. public void onResume() {super.onResume(); // your code}'그러나 나는 그것이 당신의 문제라고 생각하지 않습니다. – Hassan

+0

어떤 라인에서 예외가 발생합니까? – Hassan

+0

main.xml 파일 표시 – 5hssba

답변

0

내가 당신이 원하는 무슨 생각입니다 다른 기능의 코드. 그런 다음 XML에서 android:onClick="onButtonDownClick"을 아래쪽 버튼에 추가합니다. 위로 버튼에 'onButtonUpClick'을 제외하고 동일하게하십시오. 그러면 클릭시 해당 함수가 호출됩니다. 이러한 함수는 View을 인수로 사용한다는 점에 유의해야합니다.

+0

도움을 주셔서 감사합니다.하지만 내 의도를 오해 한 것 같습니다. 내가하려고했던 것은 위로 버튼을 눌렀을 때 내 이미지를 1 픽셀 위로 이동시키고 배경을 애니메이션 .gif로 설정하면 사용자가 버튼에서 손가락을 뗄 때까지 반복됩니다. 그런 다음 ACTION_UP 코드가 실행되어 배경을 캐릭터의 이미지로 다시 스왑합니다. –

+0

본인의 질문에 몇 가지 의견을 추가했습니다. 이것은 시작에 불과합니다. 완성 된 다른 3 개의 버튼에 대한 코드를 복사 하겠지만 문자를 왼쪽, 오른쪽, 아래로 움직 이도록합니다. –

+0

오. 내 실수, 너를 오해 했어. 여기에 두 번째 답변을보십시오 : http://stackoverflow.com/questions/3784514/capture-button-release-in-android. 나는 그것이 당신이하려는 것을 할 수도 있다고 생각합니다. – Hassan