[英]sending data from activity to fragment
按下側面菜單時,我有一個側面菜單。 它應該使用SharedPreferences
String
並將其發送到Fragment
。 並且Fragment
應該設置TextView
並將其顯示在MainActivity
。
發送到片段的數據未顯示在MainActivity
,我收到了錯誤。 有什么辦法嗎?
主要活動代碼(按選項時):-
if(num == 0)
{
SharedPreferences sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
FragmentOne F1 = new FragmentOne();
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
F1.setTextV(username);
FT.commit();
}
分段
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
return v;
}
public void setTextV(String username)
{
textV.setText(username);
}
當前實施中存在以下問題:
1.如果fragment_one
處於從onCreateView
返回的布局中,則使用v
調用findViewById:
View v = inflater.inflate(R.layout.fragment_one, container, false);
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
return v;
2.在FT.commit();
之后調用setTextV
FT.commit();
:
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
F1.setTextV(username);
因為您要從SharedPreferences
獲取值以在TextView中顯示,所以要從onCreateView
Preferences中獲取值並在TextView中顯示。
在這種特殊情況下,您不需要將數據發送到片段,因為在片段中,您可以訪問SharedPreferences。
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
SharedPreferences sp = getActivity().getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
textV.setText(username);
return v;
}
對於其他情況,將信息從活動發送到片段的最佳方法是使用捆綁包。
if(num == 0)
{
SharedPreferences sp = getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
FragmentOne F1 = new FragmentOne();
Bundle bundle = new Bundle();
bundle.putString("username", username);
// You can add all the information that you need in the same bundle
F1.setArguments(bundle);
FragmentManager FM = getFragmentManager();
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
}
分段:-
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
View v = inflater.inflate(R.layout.fragment_one, container, false);
textV.setText(getArguments().getString("username", ""));
return v;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.