2013-03-04 33 views
1

我正在嘗試通過Drag和Touch Listener創建簡單的應用程序。但是當我通過內部類將TouchListener設置爲TextView控件時,獲取NullPointerException:這裏是代碼。NULL在Android中實現Touch Listener時出現指針異常

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的視圖。但是,在撥打setContentView()之前,您嘗試使用findViewById(),這會導致option1獲得空值,因爲當前沒有充氣佈局。重新排列報表應該解決這個問題

相關問題