2016-10-01 5 views
-2

프래그먼트 2에서 MainActivity 함수 Ask()를 호출하려고합니다. 어떻게 fragment2에서 MainActivity의 함수를 호출 할 수 있습니까? 결과를 fragment2에서 호출 된 페이지로 가져 오려고합니다.프래그먼트에서 Activity 함수 호출

편집 : 이미 토론을 보았지만 내 문제의 해결책은 없습니다.

+0

[단편에서 활동 방법 불러 오기] 가능한 복제본 (http://stackoverflow.com/questions/12659747/call-an-activity-method-from-a-fragment) –

+0

' getActivity()'를 호출하고 MainActivity로 캐스팅합니다. 단편과 액티비티를 분리 할 때 인터페이스를 사용하는 것이 좋습니다. http://stackoverflow.com/a/31798511/4409409 –

+0

인터페이스를 사용하여 주요 활동. –

답변

0

해당 함수를 정적으로 설정하면 조각에서 해당 함수에 액세스 할 수 있습니다. 예 : MainActivity.Ask();

조각에서 activty에
0

:

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

건배!

+0

이전에 이미이 방법을 시도했지만 코드에서 작동하지 않습니다. – Question

+0

@Question, 여기에 코드를 작성한 다음 우리 (StackOverFlow)가 코드에 무엇이 잘못되었는지 보거나 이해할 수 있습니다. –

0

나는 this documentation을 읽는 것이 좋습니다.

(2)에서 MainActivity의 Ask() 함수를 호출하십시오.

이렇게하려면 fragment2interface을 만들어야합니다. 아래 코드는 문서의 예제입니다. 조각에서도 onAttach 메서드를 무시하면 안됩니다.

public class Fragment2 extends ListFragment { 
    OnCallActivityListener mCallback; 

    // Container Activity must implement this interface 
    public interface OnCallActivityListener { 
     public void callAskMethod(); 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 

     // This makes sure that the container activity has implemented 
     // the callback interface. If not, it throws an exception 
     try { 
      mCallback = (OnCallActivityListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
        + " must implement OnHeadlineSelectedListener"); 
     } 
    } 

    ... 
} 

이제 단편 OnCallActivityListener mCallback 인터페이스의 인스턴스를 이용하여 callAskMethod() 방법 (또는 다른 인터페이스 방식)를 호출하여 활성에 메시지를 전달할 수있다.

예를 들어 사용자가 목록 항목을 클릭하면 다음 조각이 호출됩니다. 프래그먼트는 콜백 인터페이스를 사용하여 상위 액티비티에 이벤트를 전달합니다.

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    // Send the event to the host activity 
    mCallback.callAskMethod(); 
} 

그런 다음 호스트 활동에 인터페이스를 구현해야합니다.

public static class MainActivity extends Activity 
     implements Fragment2.OnCallActivityListener{ 
    ... 

    public void callAskMethod() { 
     // Do something here 
     ask(); 
    } 
} 

그렇습니다. fragment2 조각에서 ask() 메서드를 호출했습니다.

결과를 fragment2에서 호출 한 페이지로 가져 오려고합니다.

호스트 활동, findFragmentById()으로 Fragment 인스턴스를 캡처하여 조각에 메시지를 전달 한 후 직접 조각의 공용 메소드를 호출 할 수 있습니다.

'MainActivity'에서 결과를 호출하여 호출 할 수 있습니다.

Fragment2 fragment2 = (Fragment2) getSupportFragmentManager().findFragmentById(R.id.article_fragment); 

그래서 당신은 MainActivity에서 Fragment2의 인스턴스 값을 갖는다. 그래서 거기에서 fragment2의 공개 방법을 사용할 수 있습니다. 예를의

fragment2.doSomething(); 

에 대한

.

관련 문제