我想将 LibraryFragment 中的字符串数据发送到 LibrarySongFragment。
库片段 :
public class LibraryFragment extends Fragment {
private FirebaseRecyclerAdapter mAdapter;
@Nullable
@Override
public New onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
...
mAdapter = new LibraryAdapter(options, context);
recyclerView.setAdapter(mAdapter);
}
}
库适配器 :
public class LibraryAdapter extends FirebaseRecyclerAdapter<MyModel, LibraryAdapter.MyViewHolder> {
...
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
((FragmentActivity) context).getSupportFragmentManager().beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, new LibrarySongFragment()).commit();
}
});
}
}
}
我想在 LibraryAdapter 的 MyViewHolder 中发送标题。您可以看到"String title = getItem(getAdpaterPosition(((.getTitle((;"。只需发送到LibrarySongFragment并将其发布到fragment_song_library.xml TextView中即可。
您只需创建数据包并在片段对象中设置参数。 我已经修改了你的代码。 请参考
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = getItem(getAdapterPosition()).getTitle();
FragmentManager fragmentManager = ((Activity)context).getSupportFragmentManager();
Fragment fragment;
LibrarySongFragment librarySongFragment = new LibrarySongFragment();
Bundle bundle = new Bundle();
bundle.putString("KeyTitle",title);
librarySongFragment.setArguments(bundle);
fragmentManager.beginTransaction()
.addToBackStack(null).replace(R.id.library_coordinator, librarySongFragment).commit();
}
});
}
}
create inteface在要从中发送数据的片段中
SendMessage SM;
public interface SendMessage{
void Senddata(String message,Boolean sent);
}
将此方法重写为同一片段
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
将此片段实现到保存这些片段的活动
public class Activity extends AppCompatActivity implements sendfragment.SendMessage
将消息覆盖到活动
@Override
public void Senddata(String message,Boolean sent) {
fragtwo f = (fragtwo) getSupportFragmentManager().findFragmentByTag(tag);
if(sent==true){
Toast.makeText(this, "data transfered", Toast.LENGTH_SHORT).show();
f.displaydata(message);
}
}
为发送的数据创建公共方法
public void displaydata(String massage){
String massageformat="received data is "+massage;
}
这是在Android中片段之间进行通信的方式