1

我正在尝试通过 Drag and Touch Listeners 创建简单的应用程序。但是当我通过内部类将 TouchListener 设置为 TextView 控件时,得到NullPointerException: 这是代码。

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;
        }
    }

}
}
4

1 回答 1

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()在调用之前使用setContentView(),这会导致option1获取空值,因为当前没有膨胀的布局。重新排序语句应该可以解决这个问题

于 2013-03-04T18:27:30.270 回答