我有两个活动,每个活动都有一个片段。 我在第一个fragmrnt和第二个活动之间发送了数据(简单字符串),但我无法将其从活动发送到第二个片段。 我做错了什么?
这是获取数据的活动:
public class DiaryActivity extends AppCompatActivity {
private FragmentManager manager = getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diary);
if(savedInstanceState == null){
manager.beginTransaction().add(new EditDiaryFragment(), "tag").commit();
}
}
@Override
protected void onResume() {
super.onResume();
// get the data and pass it to the fradment... not working :(
Intent intent = getIntent();
String date = intent.getStringExtra("date");
String diary = intent.getStringExtra("diary");
Bundle bundle = new Bundle();
bundle.putString("date", date);
bundle.putString("diary", diary);
EditDiaryFragment editDiaryFragment = new EditDiaryFragment();
editDiaryFragment.setArguments(bundle);
}
}
这是需要获取数据的片段:
public class EditDiaryFragment extends Fragment implements View.OnClickListener {
private EditText diaryEditText;
private Button diarySaveButton;
private TextView diaryDateText;
private String today;
private ShvizoutDBHelper helper;
private StringBuffer buffer;
public EditDiaryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
helper = new ShvizoutDBHelper(getContext());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_edit_diary, container, false);
diaryDateText = (TextView) v.findViewById(R.id.diaryDateText);
diarySaveButton = (Button) v.findViewById(R.id.diarySaveButton);
diaryEditText = (EditText) v.findViewById(R.id.diaryEditText);
diarySaveButton.setOnClickListener(this);
Bundle bundle = getArguments();
if(bundle != null){
String bDate = bundle.getString("date");
String bDiary = bundle.getString("diary");
diaryDateText.setText(bDate);
diaryEditText.setText(bDiary);
}
return v;
}
}
感谢!!
答案 0 :(得分:0)
添加捆绑包后,您需要在活动中添加相同的EditDiaryFragment实例:
EditDiaryFragment editDiaryFragment = new EditDiaryFragment();
editDiaryFragment.setArguments(bundle);
getSupportFragmentManager.beginTransaction().add(editDiaryFragment, "tag").commit();