gpt4 book ai didi

java - 单击界面回调在 Android 中给出 null

转载 作者:行者123 更新时间:2023-11-29 07:35:03 24 4
gpt4 key购买 nike

我有 Android 模块库,它将创建 Touch Keypad UI 并为 done 和 backbutton 设置事件监听器。

还有主要的activity实现了eventCallback接口(interface)

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 Module Library)

public interface eventCallback {
void onClick();
}

touchkey.java (Android Module Library)

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 上得到空指针异常

eventCall.onClick(); (eventCall is null)

我不知道我哪里做错了。任何人都可以帮忙吗?需求:我需要在Main Activity中处理发生在Library上的点击事件

最佳答案

您必须为 eventCall 创建 setter(在 touchkey.java 中):

public void setEventCall(eventCallback eventCall) {
this.eventCall = eventCall;
}

然后,使用它(在 MainActivity 中):

View v = new touchkey(this);
setContentView(v);
((touchkey) v).setEventCall(this);

关于java - 单击界面回调在 Android 中给出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908388/

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