다른 조각으로 데이터를 전송하는 방법?


194

Fragment마찬가지로 일부 데이터를 다른 데이터로 전송하는 방법 extras은 intents무엇입니까?


나는이 질문에 @ 여기 에 대답하려고합니다 . 나는 그것이 효과가 있기를 바랍니다.
— ozhanli

답변:


482

를 사용하십시오 Bundle. 예를 들면 다음과 같습니다.

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

번들에는 많은 데이터 유형에 대한 메소드가 있습니다. 참조 이

그런 다음에서 다음을 사용하여 Fragment데이터를 검색하십시오 (예 : onCreate()방법).

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

1
귀하의 답변에 감사드립니다.하지만 Serializable 또는 Parcelable과 같은 것을 구현해야합니까?
— Ankit Srivastava

아니요, 클래스를 구현할 필요가 없습니다.
— 유전자

2
그 묶음을 확인하기 위해 체크를 추가하고 싶을 수도 있습니다!
— Niels

그리고 메모리에 기존 조각이 있다면?
— powder366

이것은 코드가 작동하지 않고 활동을 데이터가있는 조각으로 리디렉션하지 않습니다
— Venkatesh

44

Ankit이 말한 것처럼 이전 답변을 더 확장하려면 복잡한 객체에 대해 Serializable을 구현해야합니다. 예를 들어, 간단한 객체의 경우 :

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

FromFragment에서 :

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

ToFragment에서 :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

감사합니다
— 해시

1
@Sameera 나는 보통 내 프래그먼트 클래스로 문자열을 넣는다. 예를 들어 MyFragmentIMGoingTo.java 클래스를 가지고 있다면 내 TAG_TO_FRAGMENT = "MyFragmentIMGoingTo";
— mike.tihonchik

Google이 안드로이드 운영 체제에 대해보다 최적화 된 직렬화 기술로 권장하므로 Parcelable을 더 잘 사용하십시오.
— Gem

16

"아무것도 얻지 못하기"때문에 getArguments ()가 null을 반환합니다.

이 상황을 처리하려면이 코드를 사용해보십시오

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

귀하의 답변에 감사드립니다.하지만 Serializable 또는 Parcelable과 같은 것을 구현해야합니까?
— Ankit Srivastava

내가 의도를 사용하여 조각과 활동 사이에 복잡한 데이터를 전달할 때 Serializable / Parcelable을 구현해야했기 때문에 ......
— Ankit Srivastava

나는 간단한 값으로 만 시도했다. 직렬화 또는 Parcelable 미안에 대한 어떤 생각이
— Sakthimuthiah

1
대답이 아닌 의견이어야합니다!
— Gem

14

조각을 사용하여 데이터를 전달하는 완전한 코드

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

커스텀 프래그먼트 클래스에서

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

viewID를 어디서 구할 수 있습니까?
— Hoo

@Hoo : 당신이 묻고 싶은 질문을 지정하십시오
— 아난드 Savjani


5

이전 답변을 연장하는 것만으로도 누군가를 도울 수 있습니다. 귀하의 경우 getArguments()반환 null에 넣어 onCreate()당신의 조각의 생성자 방법이 아니라 :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

1
            First Fragment Sending String To Next Fragment
            public class MainActivity extends AppCompatActivity {
                    private Button Add;
                    private EditText edt;
                    FragmentManager fragmentManager;
                    FragClass1 fragClass1;


                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        Add= (Button) findViewById(R.id.BtnNext);
                        edt= (EditText) findViewById(R.id.editText);

                        Add.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                fragClass1=new FragClass1();
                                Bundle bundle=new Bundle();

                                fragmentManager=getSupportFragmentManager();
                                fragClass1.setArguments(bundle);
                                bundle.putString("hello",edt.getText().toString());
                                FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
                                fragmentTransaction.add(R.id.activity_main,fragClass1,"");
                                fragmentTransaction.addToBackStack(null);
                                fragmentTransaction.commit();

                            }
                        });
                    }
                }
         Next Fragment to fetch the string.
            public class FragClass1 extends Fragment {
                  EditText showFrag1;


                    @Nullable
                    @Override
                    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

                        View view=inflater.inflate(R.layout.lay_frag1,null);
                        showFrag1= (EditText) view.findViewById(R.id.edtText);
                        Bundle bundle=getArguments();
                        String a=getArguments().getString("hello");//Use This or The Below Commented Code
                        showFrag1.setText(a);
                        //showFrag1.setText(String.valueOf(bundle.getString("hello")));
                        return view;
                    }
                }
    I used Frame Layout easy to use.
    Don't Forget to Add Background color or else fragment will overlap.
This is for First Fragment.
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@color/colorPrimary"
        tools:context="com.example.sumedh.fragmentpractice1.MainActivity">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:id="@+id/BtnNext"/>
    </FrameLayout>


Xml for Next Fragment.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
   android:background="@color/colorAccent"
    android:layout_height="match_parent">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtText"/>

</LinearLayout>

3
답을 설명 하시겠습니까? 설명이없는 코드는 큰 도움이되지 않습니다
— Coder

흐름에 코드를 작성하여 이해할 수 있도록 ..... 번들을 사용하여 기본 활동에서 FragClass1로 데이터 전달.
— Sumedh Ulhe

1

활동 클래스에서 :

번들 인수를 사용하여 데이터를 조각으로 보내고 조각을로드하십시오.

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

myFragment 클래스에서 :

번들에서 인수를 가져 와서 XML로 설정하십시오.

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);

다시 질문을 읽어 보시기 바랍니다, 그것은 조각에 대한 조각이다
— 아민 Pinjari

1

이것이 번들을 사용하는 방법입니다.

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

번들에서 값을 검색하십시오.

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }

0

입력 조각

public class SecondFragment extends Fragment  {


    EditText etext;
    Button btn;
    String etex;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.secondfragment, container, false);
        etext = (EditText) v.findViewById(R.id.editText4);
        btn = (Button) v.findViewById(R.id.button);
        btn.setOnClickListener(mClickListener);
        return v;
    }

    View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            etex = etext.getText().toString();
            FragmentTransaction transection = getFragmentManager().beginTransaction();
            Viewfragment mfragment = new Viewfragment();
            //using Bundle to send data
            Bundle bundle = new Bundle();
            bundle.putString("textbox", etex);
            mfragment.setArguments(bundle); //data being send to SecondFragment
            transection.replace(R.id.frame, mfragment);
            transection.isAddToBackStackAllowed();
            transection.addToBackStack(null);
            transection.commit();

        }
    };



}

당신의 관점 조각

public class Viewfragment extends Fragment {

    TextView txtv;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.viewfrag,container,false);
        txtv = (TextView)  v.findViewById(R.id.textView4);
        Bundle bundle=getArguments();
        txtv.setText(String.valueOf(bundle.getString("textbox")));
        return v;
    }


}

0

프래그먼트 간 탐색을 위해 그래프를 사용하는 경우 다음을 수행 할 수 있습니다. 프래그먼트 A에서 :

    Bundle bundle = new Bundle();
    bundle.putSerializable(KEY, yourObject);
    Navigation.findNavController(view).navigate(R.id.contactExtendedFragment, bundle);

B를 단편화하려면 :

    Bundle bundle = getArguments();
    contact = (DISContact) bundle.getSerializable(KEY);

물론 객체는 Serializable을 구현해야합니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.