我正在执行一个历史记录活动,该活动将带有For循环的片段实现为线性布局。
在该历史记录活动中,我有一个水平滚动条,当我单击视图时,它将返回该视图的索引。然后,我由侦听器将其发送给一个片段,但是问题是我有多个片段,并且只有一个片段正在获得响应。我希望所有片段都接听电话。我该如何解决?
这是我在历史活动中拥有的:
OnCustomEventListener mListener;
View.OnClickListener myClickListener = new OnClickListener(){
@Override
public void onClick(View v) {
// here is where I get the index of the scroll bar
indexChild = ((ViewGroup) uno.getParent()).indexOfChild(v);
// here is where I call the method of the interface
mListener.onEvent(indexChild);
}};
// here is where i set the fragments to the linear layout
for(i = 0; i<cant;i++){
if(Utils.History_Thread == false) {
final Fragment Frag = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt("dispositivo", dev);
bundle.putInt("row",i);
Frag.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, Frag).commit();
try {
sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
这是片段:
public class PlaceholderFragment extends org.holoeverywhere.app.Fragment
implements ScrollViewListener,OnCustomEventListener {
private static LinearLayout padre;
OnHeadlineSelectedListener mCallback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
more.. implementations
// here is when i implement the listener of mListener of History Activ.
((History)activity).mListener = this;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " implement headlistener);
}
}
// here I override the method and set the background color of the view I want
@Override
public void onEvent(int index) {
padre.getChildAt(index).setBackgroundColor(Color.GREEN);
}
}
仅调用了一个片段,因此仅绘制了该片段的视图。
接口
public interface OnCustomEventListener{
public void onEvent(int index);
}
这是正在发生的情况的图片:
我希望所有人都被涂成绿色。
实际上,for的最后一个片段已绘制完毕,也许有帮助。
我通常喜欢使用诸如greenrobot的EventBus之类的库。它确实使不同组件之间的通信非常整洁,还使处理后台/ UI线程更容易。它节省了很多重复的代码和接口,并由使用它的社区进行了测试。
例:
// sender (activity or other)
EventBus.getDefault().post(new ClickEvent(index));
// receiver (fragments, or other)
EventBus.getDefault().register(this); // in onCreate()
EventBus.getDefault().unregister(this); // in onDestroy()
public void onEvent(ClickEvent clickEvent) { ... }
包含其他信息的幻灯片:http : //www.slideshare.net/greenrobot/eventbus-for-android-15314813
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句