我试图通过拖拽和触摸监听器创建简单的应用程序。但是,当我通过内部类将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;
}
}
}
}发布于 2013-03-05 02:27:30
更改:
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获得空值,因为当前没有膨胀的布局。对语句重新排序应该可以解决这个问题
https://stackoverflow.com/questions/15208408
复制相似问题