2016-08-02 1 views
0

私は1つのMainActivityと2つのフラグメントを持つアプリを持っています。これらの断片は、MainActivityに、このように引数を送信します。Android - フラグメントを決定する

Bundle args = new Bundle(); 
args.putLong("id",id); 
sf.setArguments(args); 

そしてMainActivityは、どのように私はMainActivityにこの引数を送信したフラグメントを決定することができます

protected void onCreate(Bundle savedInstanceState) { 
    private long wayId = getArguments().getLong("id"); 
} 

onCreate()方法で引数を取りますか?

答えて

1

別の引数をフラグメントのタグと同様にバンドルに追加できます。

Bundle args = new Bundle(); 
args.putLong("id",id); 
args.putString("fragmentTag", fragmentTag); 
sf.setArguments(args); 

とあなたがあなたの活動のすべてのフラグメントのために、その後

public class FragmentA extends Fragment { 
    public static interface FragmentAInterface { 
     void doSomething(String data); 
    } 
} 
public class FragmentB extends Fragment { 
    public static interface FragmentBInterface { 
     void doSomething(String data); 
    } 
} 

とを別々のinrterfaceを定義することができ

+0

私が知っていますそれはgetClassのようなものを使う方法がありますか? – gigs

+0

はい、this.getClass()を使用することができます。フラグメントクラスの名前が一意の場合は、それを識別子として使用できます。 – br00

+0

また、fragment.getTag()を使用することもできますが、fragmentTransaction.add(R.id.fragment_container、fragment、 "your_tag")のように、フラグメントの作成中にタグを割り当てる必要があります。 – br00

1

あなたのonCreate()内のタグをretrive:

public class MyActivity extends AppCompatActivity implements FragmentA.FragmentAInterface, FragmentB.FragmentBInterface{ 

    @Override 
    public void doSomething(String data) { 
     //Guaranteed to come from Fragment A 
    } 

    @Override 
    public void doOtherThing(String data) { 
     //Guaranteed to come from Fragment B 
    } 
} 
関連する問題