嗨,大家好我是從Android世界開始的,正如問題所暗示的那樣,我卡在那裏。我做了一些研究,並嘗試了一些在這個社區發佈的答案,但我無法弄清楚。如何從活動中發送數據並將其存入片段
我有一個活動,顯示聯繫人列表中的每個項目導航到細節視圖一旦被點擊。我的目標是通過de item id來執行請求並顯示響應。
這裏是我的嘗試:
public class PersonDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
// This variables have the right value
String personName = intent.getStringExtra("personName");
String personID = intent.getStringExtra("personID");
Bundle bundle = new Bundle();
// I'm trying to send this variable to make a request later
bundle.putString("personID", personID);
// Set Fragment Arguments
PersonDetailFragment fragment = new PersonDetailFragment();
fragment.setArguments(bundle);
setContentView(R.layout.persons);
}
}
public class PersonDetailFragment extends Fragment {
public PersonDetailFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This throw me a NPE
String data = null;
if (getArguments() != null) {
data = getArguments().getString("personID");
}
final View rootView = inflater.inflate(R.layout.person_detail_list, container, false);
return rootView;
}
}
在此先感謝球員
我想補充的'your_fragment_container'必須加入到'layout.persons' XML,而不是添加了''本身的佈局。更多信息[這裏](https://developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime)。 –
感謝男人,它像一個魅力=) –