gpt4 book ai didi

Android 事件总线不适用于两个事件监听器

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:03:39 33 4
gpt4 key购买 nike

在我的 Android 应用程序中,我为 ListView 使用了一个 Activity 和 Adapter,我的要求是需要使用 EventBus 通过事件监听器与适配器类和 Activity 进行通信,因此我创建了两个事件监听器类。

我的流程是:

1) 我在 Activity 中有一个按钮,该按钮应该与 Adapter 类通信。

2) 如果我点击 TextView ( ListView 的 TextView 小部件)应该与 Activity 类通信。

通过以下代码,它适用于 Adapter 与 Activity 通信,但 Activity 不与适配器类通信。请帮助我如何在两个类(class)进行交流?

我已经发布了完整的示例项目代码:

Activity 类:

    public class ListMobileActivity extends Activity {....};

private ListView list;
private Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(ListMobileActivity.this);
......
list.setAdapter(adapter);

// Does not communicates with Adapter.
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EventBus.getDefault().post(new TestEvent2("test event"));
}
});
}

public void onEvent(TestFinishedEvent event) {
Log.e("TestFinishEvent ", event.test);
}

}

适配器类:

public class MobileArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;

public MobileArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_mobile, values);
this.context = context;
this.values = values;
EventBus.getDefault().register(this.context); // registered here.
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View rowView = inflater.inflate(R.layout.list_mobile, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
.........
// its works, communicate with Activity
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
EventBus.getDefault().post(new TestFinishedEvent("ssds"));
}
});
return rowView;
}

public void onEvent(TestEvent2 event) {
Log.e("Test event 2 ", event.test);
}
}

最佳答案

不要每次都创建新的 EventBus 实例,使用 EventBus.getDefault()。添加到两个类方法 public void onEvent(Object event)

关于Android 事件总线不适用于两个事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059531/

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