안녕하세요, 저는 안드로이드 세계에서 시작하고 있습니다. 질문에서 알 수 있듯이, 저는 거기에 머물러 있습니다. 나는 약간의 연구를했고,이 공동체에 게시되었던 대답의 약간을 시험해 보았다. 그러나 나는 그것을 이해할 수 없다.액티비티에서 데이터를 가져 와서 파편으로 가져 오는 방법
연락처 목록을 표시하는 활동이 있으며 목록의 모든 항목이 한 번 상세보기로 이동합니다. 내 목표는 항목 ID를 전달하여 요청을 수행하고 응답을 표시합니다. 사전들
안녕하세요, 저는 안드로이드 세계에서 시작하고 있습니다. 질문에서 알 수 있듯이, 저는 거기에 머물러 있습니다. 나는 약간의 연구를했고,이 공동체에 게시되었던 대답의 약간을 시험해 보았다. 그러나 나는 그것을 이해할 수 없다.액티비티에서 데이터를 가져 와서 파편으로 가져 오는 방법
연락처 목록을 표시하는 활동이 있으며 목록의 모든 항목이 한 번 상세보기로 이동합니다. 내 목표는 항목 ID를 전달하여 요청을 수행하고 응답을 표시합니다. 사전들
시도 :
public void onItemClick(ItemView itemView) {
personId = itemView.getPersonId();
Fragment detailFragment = PersonDetailFragment.newInstance(personId);
getSupportFragmentManager()
.beginTransaction()
.replace(your_fragment_container, detailFragment)
.commit();
}
다음 단계는 조각 초기화입니다. 단편 작성에 정적 메소드를 사용하는 것이 좋습니다. 적절한 조각 클래스에서이 방법을 쓰기 :
public static PersonDetailFragment newInstance(String personId) {
Bundle args = new Bundle();
args.putString("personId", personId);
PersonDetailFragment fragment = new PersonDetailFragment();
fragment.setArguments(args);
return fragment;
}
에서
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;
}
}
덕분에 당신이 Fragment
인스턴스를 생성 한 후 모든 변수를 전달 할 필요가없는 경우,이 같은 생성자에 매개 변수를 전달 :
여기 내 시도이다.
PersonDetailFragment fragment = new PersonDetailFragment(personID);
이 같은 조각의 생성자가되는 :
public PersonDetailFragment(String personID) {
// Required empty public constructor
}
을 당신이 인터페이스를 구현할 수있는 활동을 지속적으로 의사 소통을합니다. 이 기사를 읽으십시오, 그들과 함께 시작하는 것이 좋은 지적입니다, listeners
.
https://developer.android.com/training/basics/fragments/communicating.html
당신은 당신의 활동에 조각을 추가하지 않는 것?
조각이 활동의 xml 레이아웃에있는 경우, Java에서 인수를 만들고 추가하는 것과 같은 것이 아닙니다.
프래그먼트를 프로그래밍 방식으로 활동에 추가해야합니다. 이 같은 항목에 대한 설정 리스너에
는
그냥 추가하려면'your_fragment_container' 대신 레이아웃에''자체를 추가하는의'layout.persons' XML에 추가해야합니다. 자세한 정보는 [여기] (https://developer.android.com/training/basics/fragments/fragment-ui.html#AddAtRuntime)를 참조하십시오. –
고마워요, 그것은 매력처럼 일했습니다 =) –