부모 활동에서 Fragment 메서드 호출


124

I는 참조에 안드로이드 파편 데브 안내서 에 "활성, FragmentManager의 단편에 대한 참조를 획득하여 단편의 메소드를 호출 할 수있는 findFragmentById()findFragmentByTag()."

다음 예제는 조각 참조를 가져 오는 방법을 보여 주지만 조각에서 특정 메서드를 호출하는 방법은 보여주지 않습니다.

누구든지 이것을 수행하는 방법의 예를 줄 수 있습니까? 부모 활동의 조각에서 특정 메서드를 호출하고 싶습니다. 감사.

답변:


210

너무 간단한 질문을 정확하게 얻지 못합니다.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(); 

업데이트 : Kotlin을 사용하는 사람들을 위해

var fragment = supportFragmentManager.findFragmentById(R.id.frameLayoutCW) as WebViewFragment
fragment.callAboutUsActivity()

10
간단했습니다. 감사합니다 (나는 fragments를 처음 접했습니다). 이제 어려운 부분은 처음에 조각에 대한 참조를 얻을 수 없다는 것입니다. XML 레이아웃에 정의되어 있지 않으므로 findFragmentById ()를 사용할 수 없습니다. 그리고 내가 따르는 코드 (위 참조)에서 조각이 어떻게 / 어디에 생성되는지는 명확하지 않습니다. 그렇다면 태그를 추가하고 findFragmentByTag ()를 사용할 수 있습니다. 예제의 AccountListActivity 부분에는 beginTransaction (). add ()에 대한 호출이 있지만 추적에 따라 호출되지 않습니다. 이것은 내가 머리를 긁는 곳입니다. 어떤 제안이라도 감사합니다.
gcl1

34
조각 ID를 어떻게 얻을 수 있습니까?
Narendra Singh

8
이렇게함으로써 나는 null 객체 참조로 끝났다!
Alok Rajasukumaran

3
@Fattie, 조각 태그가 없으면 어떻게하나요?
Vaclovas Rekašius Jr.

5
XML에서 조각을 선언하지 않았으므로 조각 ID가 없습니다. 어떻게해야합니까?
akash bs

76

"import android.app.Fragment;"를 사용하는 경우 그런 다음 다음 중 하나를 사용하십시오.

1)

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name(); 

R.id.example_fragment는 XML 레이아웃 내부의 FrameLayout ID 일 가능성이 가장 높습니다. 또는

2)

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name(); 

여기서 FragTagName은 u가 수행했을 때 지정한 이름입니다.

TabHost mTabHost.newTabSpec(“FragTagName”)

"import android.support.v4.app.Fragment;"를 사용하는 경우 그런 다음 다음 중 하나를 사용하십시오.

1)

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.example_fragment); 
fragment.specific_function_name(); 

또는

2)

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name(); 

1
ID가 R.id.example_fragment 인 CoordinatorLayout이 있으며 null을 반환합니다. import android.support.v4.app.Fragment를 사용하고 있습니다. 무엇을해야합니까?
Kishore

이것을 새로운 질문으로 게시하고 샘플 코드를 포함하는 것이 좋습니다. 실제 코드를 보지 않고 문제의 원인을 말하기는 어렵습니다.
유전자

9

지원 라이브러리를 사용하는 경우 다음과 같이 할 수 있습니다.

FragmentManager manager = getSupportFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.my_fragment);
fragment.myMethod();

4
  1. 지원 라이브러리 조각을 사용하지 않는 경우 다음을 수행하십시오.

((FragmentName) getFragmentManager().findFragmentById(R.id.fragment_id)).methodName();


2. 지원 라이브러리 조각을 사용하는 경우 다음을 수행합니다.

((FragmentName) getSupportFragmentManager().findFragmentById(R.id.fragment_id)).methodName();


3

조각에서 메서드를 호출하기 전에 조각이 추가되었는지 확인하는 것이 가장 좋습니다. null 예외를 방지하려면 다음과 같이하십시오.

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
  fragment.<specific_function_name>(); 
}

2

단편에서 활동으로 :

((YourActivityClassName)getActivity()).yourPublicMethod();

활동에서 조각으로 :

FragmentManager fm = getSupportFragmentManager ();

//if you added fragment via layout xml
YourFragmentClass fragment = 
(YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();

코드를 통해 조각을 추가하고 조각을 추가 할 때 태그 문자열을 사용한 경우 대신 findFragmentByTag를 사용합니다.

YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");

1

먼저 fragment같은 방법으로 방법을 만듭니다.

public void name()
{


}

당신에 activity당신이 추가

onCreate()방법 추가

myfragment fragment=new myfragment()

마지막으로 호출하려는 메소드를 호출하십시오.

fragment.method_name();

이 코드를 시도


1
FragmentManager fm = getFragmentManager(); 
MainFragment frag = (MainFragment)fm.findFragmentById(R.id.main_fragment); 
frag.<specific_function_name>(); 

1

내가 모르는 Java만에 C#(Xamarin.Android)이 메소드를 호출하는 데 필요한 조각 매번를 검색 할 필요가 없습니다, 아래 참조 :

public class BrandActivity : Activity
{
    MyFragment myFragment;

    protected override void OnCreate(Bundle bundle)
    {       
        // ...
        myFragment = new MyFragment();      
        // ...
    }

    void someMethod()
    {
        myFragment.MyPublicMethod();
    }
}

public class MyFragment : Android.Support.V4.App.Fragment
{
    public override void OnCreate(Bundle bundle)
    {
        // ...
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle)
    {
        // ...
    }

    public void MyPublicMethod()
    {
        // ...
    }   
}

나는 Java당신도 똑같이 할 수 있다고 생각 합니다.


1

또한 다음과 같은 인터페이스를 사용하여 조각 메서드를 호출합니다.

먼저 인터페이스를 만듭니다.

public interface InterfaceName {
    void methodName();
}

인터페이스를 만든 후 조각에 인터페이스를 구현합니다.

MyFragment extends Fragment implements InterfaceName {
    @overide
    void methodName() {

    }
}

활동에서 인터페이스 참조를 생성합니다.

class Activityname extends AppCompatActivity {
    Button click;
    MyFragment fragment;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        click = findViewById(R.id.button);

        fragment = new MyFragment();

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               fragment.methodName();
            }
        });
    }
}

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