2016-11-27 4 views
0

J'ai créé un TabLayout avec une MainActivity et deux fragments dans Android. Mais comment obtenir le deuxième fragment pour recevoir l'événement de bouton et appeler la première fonction de fragment?Comment appeler Fragment une autre fonction de fragment

J'ai essayé ce qui suit, mais cela ne fonctionne pas et je demande.

public interface CustomSearchPOI { 
    void requestSearch(String query); 
} 

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    try { 
     customSearchPOI = (CustomSearchPOI)context; 
    } catch (ClassCastException ex) { 
     throw new ClassCastException(context.toString() + "must implement CustomSearchPOI"); 
    } 
} 

Deuxième Fragment de code

if(info_cursor != null) { 
     info_cursor.moveToFirst(); 
     while(!info_cursor.isAfterLast()) { 
      if(info_cursor.getInt(0) == id) { 
       out_subject.setText(info_cursor.getString(1)); 
       out_college.setText(info_cursor.getString(2)); 
       out_classroom.setText(info_cursor.getString(3)); 
       break; 
      } 
      info_cursor.moveToNext(); 
     } 
    } 
    choice_dialog.setPositiveButton(getString(R.string.Location_navigate), new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialogInterface, int i) { 
      TabsFragment.viewPager.setCurrentItem(0); 
      customSearchPOI.requestSearch(out_college.getText().toString()); 
     } 
    }); 
    choice_dialog.setNegativeButton(getString(R.string.tt_modify), new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialogInterface, int i) { 
      update_timetable_dialog(id); 
     } 
    }); 
    choice_dialog.show(); 

Code de la fonction d'appel

@Override 
public void requestSearch(String query) { 
    String FRAGMENT_TAG = "LOCATION_TAG"; 
    Fragment fragment = new MapFragment(); 
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
    fragmentTransaction.add(fragment, FRAGMENT_TAG).commitAllowingStateLoss(); 
    try { 
     ((MapFragment)getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG)).searchPOI(query); 
    } catch(NullPointerException ex) { 
     ex.printStackTrace(); 
     Log.d("[TAG]", fragment.getTag()); 
    } 
} 

code MainActivity

public void searchPOI(String query) { 
    query = Searchcheck(query); 
    TMapData data = new TMapData(); 
    if(!TextUtils.isEmpty(query)) { 
     data.findAllPOI(query, new TMapData.FindAllPOIListenerCallback() { 
      @Override 
      public void onFindAllPOI(final ArrayList<TMapPOIItem> arrayList) { 
       getActivity().runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         tMapView.removeAllMarkerItem(); 
         for (TMapPOIItem poi : arrayList) { 
          addMarker(poi); 
         } 
         if(arrayList.size() > 0) { 
          TMapPOIItem poi = arrayList.get(0); 
          moveMap(poi.getPOIPoint().getLatitude(), poi.getPOIPoint().getLongitude()); 
          if(poi.getPOIPoint().getLatitude() > 36.832311 && poi.getPOIPoint().getLongitude() < 127.165038) { 
           Snackbar.make(coordinatorLayout, getString(R.string.No_place), Snackbar.LENGTH_LONG).show(); 
           if(location_me.getVisibility() != View.INVISIBLE) { 
            location_me.hide(); 
           } 
           return; 
          } 
          dst = new TMapPoint(poi.getPOIPoint().getLatitude(), poi.getPOIPoint().getLongitude()); 
          searchRoute(src, dst); 
         } 
        } 
       }); 
      } 
     }); 
    } 
} 

premier Fragment de code (fonction à appeler)

Selon la documentation de développement de Google, la communication directe entre fragments et fragments est impossible.

Ainsi quand j'essaye d'appeler la fonction de fragment de Fragment par l'activité, j'obtiens l'erreur de NullPointerException.

J'ai utilisé la syntaxe try catch pour voir s'il y avait une erreur dans le nom du tag ou une erreur dans la requête, mais aucun d'eux n'était un problème.

+0

pourquoi ne pas créer une interface dans un fragment et mettre en œuvre dans un autre? – BiGGZ

+0

Avez-vous également besoin d'implémenter le second fragment? Mais comment déplacez-vous ViewPager dans TabLayout? –

+0

mieux encore, puisque les deux fragmnts sont dans la même activité, pourquoi ne pas y mettre votre méthode à la place? – BiGGZ

Répondre

1

FragmentX:

public class MyFragment extends Fragment{ 

    interface MyInterface{ 

     void doSomething(); 
    } 

    public void someMethodInYourFragment(){ 
    ((MyInterface)getContext()).doSomething();//throws ClassCastException if not implemented in Activity 
    } 

} 

Classe X:

public class MyActivity extends Activity implements MyFragment.MyInterface{ 

    @Override 
    public void doSomething(){ 
    //do stuff here 
    } 
} 
+0

J'ai corrigé le code dans la colonne de la question. Est-ce le bon code? Si vous le faites, vous obtiendrez une erreur NullPointerException. –

+0

Je ne suis pas ... donc votre code fonctionne maintenant? – BiGGZ

+0

Encore une erreur NullPointerException .. –