我有Android模块库,它将创建Touch Keypad UI并为完成和后退按钮设置事件监听器。
还有实现eventCallback接口的主要活动
MainActivity.java(Appication)
public class MainActivity extends AppCompatActivity implements eventCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new touchkey(this);
setContentView(v);
}
@Override
public void onClick() {
Log.i("test","complete");
Toast.makeText(this, "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
}
eventCallback.java(Android模块库)
public interface eventCallback {
void onClick();
}
touchkey.java(Android模块库)
public class touchkey extends RelativeLayout{
private static touchkey INSTANCE;
TextView bclear;
ImageView bdone;
eventCallback eventCall;
public touchkey(Context context) {
super(context);
initialize(context);
}
public touchkey(Context context, AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public void test() {
Log.i("test","test");
}
private void initialize(Context context) {
inflate(context, R.layout.touchkey, this);
bclear = (TextView) findViewById(R.id.anti_theft_t9_key_clear);
bdone = (ImageView) findViewById(R.id.anti_theft_t9_key_done);
bdone.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (eventCall != null) {
eventCall.onClick();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
但是我在touchkey.java上获得了nullpointer异常
eventCall.onClick(); (eventCall为null)
我不知道我做错了什么。任何人都可以帮忙。要求:我需要处理主要活动中的库中发生的点击事件
答案 0 :(得分:5)
您必须为eventCall创建setter
(在touchkey.java中):
public void setEventCall(eventCallback eventCall) {
this.eventCall = eventCall;
}
然后,使用它(在MainActivity中):
View v = new touchkey(this);
setContentView(v);
((touchkey) v).setEventCall(this);