我制作了Android蓝牙聊天教程。我想在其他类(MyCursorAdapter.class)中使用OnClickListeners,而不是在主要活动中使用OnClickListeners。
我认为这是一个非常简单的java问题。但我不知道如何实现这个(我如何使用我班级中其他活动的mHandler)。
任何人都可以帮我吗?
Cheers Felix
MainActivity.class中的来源(运作良好)
public class MainActivity extends ListActivity {
private BluetoothService mChatService = null;
...
private void setupChat() {
mButton1 = (Button) findViewById(R.id.button1);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
byte[] out = {32};
mChatService.write(out);
mChatService = new BluetoothService(this, mHandler);
}
});
}
来源MyCursorAdapter.class(这里我想实现相同的功能)
public class MyCursorAdapter extends ResourceCursorAdapter implements OnClickListener {
...
private class OffItemClickListener implements OnClickListener {
private int position;
public OffItemClickListener(int position) {
super();
this.position = position;
}
@Override
public void onClick(View v) {
mCursor.moveToPosition(position);
// byte[] out = {32};
// MainAcitivity.talkChat(out);
// error: "non-static variable this cannot be referenced from a static context"
// Here i want to the the same like in the MainActivity class.
// But how can I connect to the mHandler?
}
}
}
注释:
MainActivity中MyCursorAdapter的实例
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
adapter = new MyCursorAdapter(this, notesCursor);
setListAdapter(adapter);
}
评论评论:
或者如何从MyCursorAdapter调用此MainActivity方法?:
public void talkChat(byte[] out) {
mChatService.write(out);
mChatService = new BluetoothService(this, mHandler);
}
答案 0 :(得分:3)
在MyCursorAdapter类中创建mhandler的实例
public class MyCursorAdapter extends ResourceCursorAdapter implements
OnClickListener {
private Handler mHandler;
public void setMHandler(Handler mHandler){
this.mHandler = mHandler;
private class OffItemClickListener implements OnClickListener {
private int position;
public OffItemClickListener(int position) {
super();
this.position = position;
}
@Override
public void onClick(View v) {
mCursor.moveToPosition(position);
// byte[] out = {32};
// MainAcitivity.talkChat(out);
// error: "non-static variable this cannot be referenced from a static context"
Use your mhandler...
// Here i want to the the same like in the MainActivity class.
// But how can I connect to the mHandler?
}
}
}
并从您的MainActivity中引用它
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
adapter = new MyCursorAdapter(this, notesCursor);
adapter.setMHandler(mHandler); //Reference
setListAdapter(adapter);
}