我一直在为Android开发一个简单的触摸处理程序,可以像onUpdate(当触摸屏幕时)触发回调,而无需设置线程。我的问题是,我对Java的知识是相当有限的,我不能这样做,因为我对如何使用接口知之甚少。我敢肯定,我的问题可能是一个简单的错字或什么的,但我得到一个NullPointerException当我从触摸处理程序(处理触摸信息)执行该方法,以便我可以做我需要的主要活动类。Java,使用接口作为回调
这是主类代码(剪切从无关紧要的东西):
//package and imports
public class Test extends Activity implements TouchHelper {
StringBuilder builder = new StringBuilder();
TextView textView;
TouchReader touchReader;
List<TouchTable> touchTablesArray;
TouchTable touchTable;
public static final String Tag = "TouchTest";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
Log.d(Tag, "TextView initialized " + textView);
textView.setText("Touch and drag (multiple fingers supported)!");
touchReader = new TouchReader(textView);
Log.d(Tag, "touchReader initialized");
touchTablesArray = touchReader.getTouchTables();
setContentView(textView);
}
@Override
public void onTouchUpdate(int pointerId)
{
Log.d(Tag, "onTouchUpdate called");
touchTable = touchTablesArray.get(pointerId);
Log.d(Tag, "touchTable get successful");
//writing on stringbuilder
}
}
这是处理程序本身的代码:
//package and imports
public class TouchReader implements OnTouchListener
{
public final static String Tag = "TouchReader";
List<TouchTable> touchTables;
TouchHelper helper;
TouchTable touchTable = new TouchTable();
public TouchReader(View view)
{
view.setOnTouchListener(this);
touchTables = new ArrayList<TouchTable>(10);
Log.d(Tag, "TouchReader initialized");
}
public boolean onTouch(View v, MotionEvent event)
{
synchronized(this)
{
//all the common code handling the actual handling, with switches and such
touchTables.add(pointerId, touchTable); //obviously the pointerId is defined earlier
Log.d(Tag, "Values updated");
helper.onTouchUpdate(pointerId); //the exception is here
Log.d(Tag, "Update called");
}
return true;
}
public List<TouchTable> getTouchTables()
{
synchronized(this)
{
return touchTables;
}
}
}
正如你所看到的错误是最有可能由于我无法正确使用界面,但所有的官方文档让我更加困惑。
最后,接口的微小代码:
//package
public interface TouchHelper
{
public void onTouchUpdate(int pointerId);
}
我希望这个问题不是太noobish它张贴在这里:)
编辑:感谢所有的帮助,在最后我跟着布吉的解决方案。
谢谢,这工作像一个魅力。显然这个错误是愚蠢的,但是因为我知道“实例化”,一个接口的工作方式与我失去的普通课程不同。 – Lama 2012-07-21 19:17:18