2014-11-25 3 views
0

이것은 이미 대답했을지 모르지만 나는 아직도 이와 같은 기능에 문제가 있습니다. 내가 액티비티 A액티비티 B이라고 가정 해 봅시다. B는 viewpager을 포함하고 있습니다. activity B이 가지고있는 조각에서 함수를 호출하고 싶습니다. activity A입니다.활동에서 다른 활동의 프래그먼트로 메소드를 호출하십시오. 적절한 방법은 무엇입니까?

액티비티와 프래그먼트간에 통신하기 위해 콜백을 여러 번 사용했지만, 단 한 번만 프래그먼트와 그 홀더 활동이었습니다. 정적 메서드 (콜백 수신기는 어쨌든 정적 일 수 없습니다)를 만들고 싶지 않아서 저에게 두통이 생깁니다. 조각에서 정적 메서드를 만들고 다른 개체에서 호출 한 간단한 정적 솔루션은 실제로 잘 작동하지만 정적 인 몇 가지 사항을 변경해야 할 때 좋은 생각인지 확실하지 않습니다.

그래서 활동 B 사이의 단편 괜찮 연통하지만 활동이 메소드를 호출 할 수있다.

활동 B :

public class ActivityB extends FragmentActivity implements Fragment1.OnWhateverListener       
          { 
... 

@Override 
    public void onWhateverSelected(int position) { 
     //stuff, here I can call any function in Fragment 1 
    } 

} 

다음 코드는 잘못된 솔루션 (작동도 나던)하지만 내가하고 싶은 것이 더 나은 사진을 만든다.

활동 A :

ActivityB ab = new ActivityB(); 
ab.onWhateverSelected(number); 

그래서 이것을 어떻게 할 수? 감사합니다.

편집

활동 A는 :

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ... 
    ... 
    processIntent(getIntent()); //last line of onCreate, always gets called here 
    } 


    @Override 
    public void onNewIntent(Intent intent) { 
      super.onNewIntent(intent); 
      processIntent(intent); // this never gets called here only in OnCreate 
    } 

    private void processIntent(Intent intent) { 
       Bundle args = intent.getBundleExtra("args"); 
       if (args != null) { // check if ActivityB is started to pass data to fragments 
        String id = args.getString("ID"); 


      Log.i("ID_FROM", "id: " + id); //works well 
         if (id != null) { 
          List<Fragment> fragments = new ArrayList<Fragment>(); 
          fragments = getSupportFragmentManager().getFragments(); 
         //NULLPOINTER for the following line 
          FragmentMainDiscover fr = (FragmentMainDiscover) fragments.get(0); 
          fr.RefreshHoverView(id); 
         } 
        } 
       } 

답변

0

당신은 정적을 멀리하는 것이 옳다 : 방법은 내가

Bundle args = new Bundle(); 
    args.putString("ID", id); // the data to send 
    Intent frag_args = new Intent(Intent.ACTION_VIEW); 
    frag_args.setClass(this, MainActivity.class); 
    frag_args.putExtra("args", args); 
    startActivity(frag_args); 

활동 B 호출합니다. 너무 위험하여 화면에 표시되거나 표시되지 않을 수있는 시각적 개체.

나는 목표 조각의 부모이므로 활동 B를 진행할 것을 권장합니다. 활동 B를 시작하는 인 텐트를 작성하고, 활동 B에 대상 조각에 대해 수행해야 할 작업을 알려주는 추가 의도를 포함시킵니다. 그런 다음 B 액티비티는 프래그먼트가 표시되는지 확인하고 해당 정보를 전달합니다.

정보를 조각에 전달하는 또 다른 아이디어는 직접 호출이 아닌 setArguments를 사용하는 것입니다. 이것은 액티비티와 그 프래그먼트가 메모리에서 제거되면 안드로이드가 자동으로 인수를 복원하기 때문에 좋은 접근법입니다.

의미가 있습니까? 코드를 원합니까?

편집

인수를 사용하려면, 당신은 여전히 ​​활동 A가 활동 B.를 통해 이동이 필요합니다이것은 액티비티 A가 액티비티 B와 그 모든 프래그먼트가 인 텐트를 전송하지 않는 한 실행 중인지 여부를 알지 못하기 때문입니다. 그러나 단편을 대상으로하여 대상 데이터를 포함시킬 수 있습니다. 이와 같이 :

public class ActivityA extends Activity { 
    public static final String KEY_FRAG = "frag"; // tells activity which fragment gets the args 
    public static final String KEY_ARGS = "args"; 
    public static final String KEY_MY_PROPERTY = "myProperty"; 

    public void foo() { 
     Bundle args = new Bundle(); 
     args.putString(KEY_FRAG, "frag1Tag"); // which fragment gets the data 
     args.putCharSequence(KEY_MY_PROPERTY, "someValue"); // the data to send 

     // Send data via an Intent, to make sure ActivityB is running 
     Intent frag_args = new Intent(Intent.ACTION_VIEW); 
     frag_args.setClass(this, ActivityB.class); 
     frag_args.putExtra(KEY_ARGS, args); 
     startActivity(frag_args); 
    } 
} 

public class ActivityB extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     //TODO configure activity including fragments 
     processIntent(getIntent()); // this call is in case ActivityB was not yet running 
    } 

    @Override 
    public void onNewIntent(Intent intent) { 
     super.onNewIntent(intent); 
     processIntent(intent); // this call is in case ActivityB was already running 
    } 

    private void processIntent(Intent intent) { 
     Bundle args = intent.getBundleExtra(ActivityA.KEY_ARGS); 
     if (args != null) { // check if ActivityB is started to pass data to fragments 
      String fragTag = args.getString(ActivityA.KEY_FRAG); 
      if (fragTag != null) { 
       Fragment frag = getSupportFragmentManager().findFragmentByTag(fragTag); 
       frag.setArguments(args); 
       //TODO either show the fragment, or call a method on it to let it know it has new arguments 
      } 
     } 
    } 
} 

public class Fragment1 extends Fragment { 
    public static final String TAG = "frag1Tag"; 
    @Override 
    public void onResume() { 
     super.onResume(); 
     Bundle args = getArguments(); 
     String value = args.getString(ActivityA.KEY_MY_PROPERTY); 
     ... 
    } 
} 
+0

내가 삽입 한 코드로 내 질문을 편집했습니다. 표시된 줄에 nullpointer가 생기는 문제입니다. 다른 컨텍스트에서이 코드를 사용하면 조각을 정확하게 찾습니다. 나는 또한 NewIntent 재정의 된 메서드가 호출되지 않는다는 것을 알지 못합니다. OnCreate 만 실행됩니다. 아마 nullpointer가 발생할 수 있습니다. –

+0

어쨌든 다른 Activity를 시작하지 않으려 고합니다. 그냥 메서드를 호출하십시오. 나는 frag_args.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);를 넣을 수 있습니다. 그러나 이것은 현재 활동을 제거합니다. –

관련 문제