gpt4 book ai didi

android - 在 Android 中实现 Touch Listener 时出现空指针异常

转载 作者:行者123 更新时间:2023-11-29 14:51:56 24 4
gpt4 key购买 nike

我正在尝试通过拖动和触摸监听器创建简单的应用程序。但是当我通过内部类将 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;
}
}

}
}

最佳答案

改变:

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

关于android - 在 Android 中实现 Touch Listener 时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com