2016-08-02 6 views
0

하나의 MainActivity와 2 개의 Fragments가있는 앱이 있습니다. 어떻게 MainActivity이 인수를 전송하는 단편 확인할 수 있습니다안드로이드 - 조각 결정

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

그리고 MainActivity는 onCreate() 방법

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

에 인수를 취이 조각은 MainActivity에이 방법으로 인수를 보내?

답변

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()에서 태그를 가져 오지 :

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 
    } 
}