所以,我确实有两个片段,片段A和片段B.两者都有列表视图。当你从片段A转到片段B时,有一个产品列表视图。当你点击一个产品时,它应该用这一个产品填充片段A的列表视图,你应该可以这样做几次。
所以,我的问题是:
PS:我尝试使用事件总线但失败了。
答案 0 :(得分:0)
您应该使用侦听器接口机制在您的片段之间与您的活动进行通信。
假设MainActivity包含FragmentA和FragmentB:
让活动知道在FragmentB上选择了哪个产品:
public class MainActivity extends AppCompatActivity implements FragmentBListener {
...
@Override
public void onProductSelected(Product product) {
showFragmentAWithProduct(product);
}
private void showFragmentAWithProduct(Product product) {
// Logic to show FragmentA
}
}
public class FragmentB extends Fragment {
private FragmentBListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
yourListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product product = // Get the selected product
mListener.onProductSelected(product);
}
});
...
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (FragmentBListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement " + FragmentBListener.class.toString());
}
}
public interface FragmentBListener {
void onProductSelected(Product product);
}
}
要将参数传递给FragmentA或B,您可以使用这些参数公开一个公共方法来刷新片段,或者您可以使用参数来实例化Fragment:
public class FragmentX extends Fragment {
public static FragmentX newInstance(Param1 param1, Param2 param2) {
FragmentX fragment = new FragmentX();
Bundle args = new Bundle();
args.putXXX(key1, param1);
args.putXXX(key2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
Param1 param1 = getArguments().getXXX(key1);
Param2 param2 = getArguments().getXXX(key2);
...
}
}
...
}