활동에서 조각으로 개체 전달
나는이 Activity
를 사용하는을 Fragment
. 나는 단순히 이것 Activity
에서 객체를 Fragment
.
어떻게 할 수 있습니까? 지금까지 리소스에서 데이터를 검색하는 모든 자습서.
편집하다 :
좀 더 정확 해 봅시다 :
내 활동은 ListView
왼쪽 부분에 있습니다. 당신이 그것을 클릭하면 아이디어는 Fragment
오른쪽 부분에 로드하는 것 입니다.
나는이를 입력하면 Activity
, 객체는 Category
관통 주어진다 Intent
. 이 개체에는 다른 개체 Questions
목록 (문자열 목록 포함)이 포함됩니다. 이러한 Questions
개체는 ListView에 표시됩니다. 나는에서 하나 개의 항목을 클릭하면 ListView
, 나는의 목록 표시 할 String
에 Fragment
(A로를 ListView
).
이를 위해, 나는 전화 setContentView()
내에서 Activity
레이아웃으로. 이 레이아웃에서는 Fragment
호출 할 올바른 클래스로 정의됩니다 . 이것을 호출 setContentView()
하면 onCreateView()
of my Fragment
가 호출되지만 getArguments()
이때는 null을 반환합니다.
전화하기 전에 어떻게 채울 수 onCreateView()
있습니까? (잘 모르겠 으면 말해줘)
감사
에서 정적 메서드를 Fragment
만든 다음 getArguments()
.
예:
public class CommentsFragment extends Fragment {
private static final String DESCRIBABLE_KEY = "describable_key";
private Describable mDescribable;
public static CommentsFragment newInstance(Describable describable) {
CommentsFragment fragment = new CommentsFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(DESCRIBABLE_KEY, describable);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
mDescribable = (Describable) getArguments().getSerializable(
DESCRIBABLE_KEY);
// The rest of your code
}
나중에 Activity
다음과 같이 호출 할 수 있습니다 .
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = CommentsFragment.newInstance(mDescribable);
ft.replace(R.id.comments_fragment, fragment);
ft.commit();
전달하려는 객체 유형을 받아들이는 프래그먼트 내에 메서드를 만들어야합니다. 이 경우 이름을 "setObject"로 지정했습니다 (창조적 어? :)) 그러면 해당 메서드는 해당 객체로 필요한 모든 작업을 수행 할 수 있습니다.
MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
.commit();
} else {
fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
android.R.id.content);
}
fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
}
지원 라이브러리를 사용하고 있으며 getSupportFragmentManager ()에 대한 호출은 작업중인 항목에 따라 getFragmentManager () 일 수 있습니다.
활동 수업에서 :
public class BasicActivity extends Activity {
private ComplexObject co;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
co=new ComplexObject();
getIntent().putExtra("complexObject", co);
FragmentManager fragmentManager = getFragmentManager();
Fragment1 f1 = new Fragment1();
fragmentManager.beginTransaction()
.replace(R.id.frameLayout, f1).commit();
}
참고 : 개체는 Serializable 인터페이스를 구현해야합니다.
그런 다음 조각에서 :
public class Fragment1 extends Fragment {
ComplexObject co;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent i = getActivity().getIntent();
co = (ComplexObject) i.getSerializableExtra("complexObject");
View view = inflater.inflate(R.layout.test_page, container, false);
TextView textView = (TextView) view.findViewById(R.id.DENEME);
textView.setText(co.getName());
return view;
}
}
번들로 인수를 전달하는 것은 일부 데이터 유형으로 제한됩니다. 그러나 다음과 같은 방법으로 모든 데이터를 조각으로 전송할 수 있습니다.
조각에서 다음과 같은 공용 메서드를 만듭니다.
public void passData(Context context, List<LexItem> list, int pos) {
mContext = context;
mLexItemList = list;
mIndex = pos;
}
활동에서 조각을 인스턴스화 한 후 필요한 모든 데이터 유형으로 passData ()를 호출하십시오.
WebViewFragment myFragment = new WebViewFragment();
myFragment.passData(getApplicationContext(), mLexItemList, index);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.my_fragment_container, myFragment);
ft.addToBackStack(null);
ft.commit();
비고 : 내 프래그먼트는 "android.support.v4.app.Fragment"를 확장하므로 "getSupportFragmentManager ()"를 사용해야합니다. 물론,이 원칙은 "Fragment"를 확장하는 프래그먼트 클래스에서도 작동하지만 "getFragmentManager ()"를 사용해야합니다.
To pass an object to a fragment, do the following:
First store the objects in Bundle, don't forget to put implements serializable in class.
CategoryRowFragment fragment = new CategoryRowFragment();
// pass arguments to fragment
Bundle bundle = new Bundle();
// event list we want to populate
bundle.putSerializable("eventsList", eventsList);
// the description of the row
bundle.putSerializable("categoryRow", categoryRow);
fragment.setArguments(bundle);
Then retrieve bundles in Fragment
// events that will be populated in this row
mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");
// description of events to be populated in this row
mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");
Get reference from the following example.
1. In fragment: Create a reference variable for the class whose object you want in the fragment. Simply create a setter method for the reference variable and call the setter before replacing fragment from the activity.
MyEmployee myEmp;
public void setEmployee(MyEmployee myEmp)
{
this.myEmp = myEmp;
}
2. In activity:
//we need to pass object myEmp to fragment myFragment
MyEmployee myEmp = new MyEmployee();
MyFragment myFragment = new MyFragment();
myFragment.setEmployee(myEmp);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_layout, myFragment);
ft.commit();
If the data should survive throughout the application lifecycle and shared among multiple fragments or activities, a Model
class might come into consideration, which has got less serialization overhead.
Check this design example
This one worked for me:
In Activity:
User user;
public User getUser(){ return this.user;}
In Fragment's onCreateView method:
User user = ((MainActivity)getActivity()).getUser();
Replace the MainActivity
with your Activity Name.
참고URL : https://stackoverflow.com/questions/9931993/passing-an-object-from-an-activity-to-a-fragment
'Programing' 카테고리의 다른 글
libtool 버전 불일치 오류 (0) | 2020.11.01 |
---|---|
원하지 않을 때 curl_exec 인쇄 결과 (0) | 2020.11.01 |
QImage와 QPixmap의 차이점은 무엇입니까? (0) | 2020.11.01 |
Redirect() vs RedirectPermanent() in ASP.NET MVC (0) | 2020.11.01 |
방랑 쉘 프로 비 저너에 환경 변수 전달 (0) | 2020.11.01 |