2013-03-04 1 views
1

드래그 앤 터치 리스너를 통해 간단한 앱을 만들려고합니다. 그러나 터치 리스너를 내부 클래스를 통해 TextView 컨트롤로 설정할 때 NullPointerException : 여기 코드가 있습니다.안드로이드에서 터치 리스너를 구현하는 동안 NULL 포인터 예외가 발생했습니다.

public class MainActivity extends Activity 
{ 

private TextView option1, choice1; 

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    option1 = (TextView)findViewById(R.id.option_1);   
    setContentView(R.layout.activity_main); 
     option1.setOnTouchListener(new ChoiceTouchListener()); [NULLPOINTER] 
} 

private final class ChoiceTouchListener implements OnTouchListener 
{ 

    @Override 
    public boolean onTouch(View arg0, MotionEvent arg1) { 
     // TODO Auto-generated method stub 

     if(arg1.getAction() == MotionEvent.ACTION_DOWN) 
     { 

ClipData clipdata = ClipData.newPlainText("",""); 
DragShadowBuilder shadowbuilder = new DragShadowBuilder(arg0); 
arg0.startDrag(clipdata, shadowbuilder, arg0, 0); 
return true; 
     } 
     else 
     { 
     return false; 
     } 
    } 

} 
} 

답변

6

변경 :

protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    option1 = (TextView)findViewById(R.id.option_1);   
    setContentView(R.layout.activity_main); 
    option1.setOnTouchListener(new ChoiceTouchListener()); 
} 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    option1 = (TextView)findViewById(R.id.option_1); 
    option1.setOnTouchListener(new ChoiceTouchListener()); 
} 

findViewById()

으로는 현재 팽창 레이아웃에서 제공된 ID와보기를 찾습니다. 그러나 을 호출하기 전에 findViewById()을 사용하면 option1이 현재 부풀린 레이아웃이 없기 때문에 null 값을 얻습니다. 명령문 재정렬을 통해이 문제를 해결해야합니다.

관련 문제