一部のデータを別のフラグメントに転送する方法は?


回答:


482

を使用しBundleます。次に例を示します。

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

Bundleは、多くのデータ型用のputメソッドを備えています。これを

次に、でFragment、次のコマンドを使用して(onCreate()メソッドなどで)データを取得します。

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

1
こんにちはあなたの答えに感謝しますが、SerializableやParcelableなどの何かを実装する必要がありますか?
Ankit Srivastava

いいえ、クラスを実装する必要はありません。
ジーン

2
バンドルから何かを取得する前に、そのバンドル!= Nullを確認するためのチェックを追加する必要がありますか?
Niels

そして、あなたがメモリに既存のフラグメントを持っているなら?
パウダー366 2016年

これはコードが機能せず、アクティビティをデータでフラグメント化するようにリダイレクトされません
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 2014

GoogleがAndroidオペレーティングシステム用のより最適化されたシリアル化手法としてParcelableを推奨したので、Parcelableを使用することをお勧めします。
Gem

16

「何も取得しない」ため、getArguments()はnullを返します。

この状況を処理するためにこのコードを試してください

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

こんにちはあなたの答えに感謝しますが、SerializableやParcelableなどの何かを実装する必要がありますか?
Ankit Srivastava

インテントを使用してフラグメントとアクティビティの間で複雑なデータを渡すときにSerializable / Parcelableを実装する必要があったためです......
Ankit Srivastava

単純な値のみで試してみました。シリアライズ可能またはパーセル化可能な申し訳ありませんが申し訳ありません
Sakthimuthiah 2013

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

@フー:あなたが聞きたいことをあなたの質問に明記してください
Anand Savjani

手伝って頂けますか?stackoverflow.com/questions/32983033/...
ホー

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 2017年

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);

もう一度質問を読んでください、それはフラグメント間の問題です
アミン・ピンジャリ

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.