2011-08-22 7 views

risposta

391

Utilizzare un Bundle. Ecco un esempio:

Fragment fragment = new Fragment(); 
Bundle bundle = new Bundle(); 
bundle.putInt(key, value); 
fragment.setArguments(bundle); 

Bundle ha messo i metodi per molti tipi di dati. Vedere this

Poi, nel tuo Fragment, recuperare i dati (ad esempio in onCreate() metodo) con:

Bundle bundle = this.getArguments(); 
if (bundle != null) { 
     int myInt = bundle.getInt(key, defaultValue); 
} 
+0

Ciao grazie per la tua risposta, ma dobbiamo implementare qualcosa come Serializable o Parcelable ?? –

+0

sto passando un arraylist di un oggetto di una classe .. –

+0

No, non è necessario implementare alcuna classe. – Gene

15

getArguments() sta tornando nulla perché "La sua non ottiene nulla"

Prova questo codice per gestire questa situazione

if(getArguments()!=null) 
{ 
int myInt = getArguments().getInt(key, defaultValue); 
} 
+0

Ciao grazie per la tua risposta, ma dobbiamo implementare qualcosa come Serializable o Parcelable ?? –

+0

sto passando un arraylist di un oggetto di una classe .. –

+0

sei sicuro? Perché ho dovuto implementare Serializable/Parcelable quando stavo passando dati complessi tra un frammento e un'attività utilizzando l'intento ...... –

5

Solo per estendere Vere risposte - potrebbe aiutare qualcuno. Se i rendimenti null, metterlo a onCreate() metodo e non al costruttore del vostro frammento:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    int index = getArguments().getInt("index"); 
} 
38

Per estendere la risposta precedente ancora più, come Ankit stava dicendo, per oggetti complessi è necessario implementare Serializable. Ad esempio, per il semplice oggetto:

public class MyClass implements Serializable { 
    private static final long serialVersionUID = -2163051469151804394L; 
    private int id; 
    private String created; 
} 

In te FromFragment:

Bundle args = new Bundle(); 
args.putSerializable(TAG_MY_CLASS, myClass); 
Fragment toFragment = new ToFragment(); 
toFragment.setArguments(args); 
getFragmentManager() 
    .beginTransaction() 
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT) 
    .addToBackStack(TAG_TO_FRAGMENT).commit(); 

nel ToFragment:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 

    Bundle args = getArguments(); 
    MyClass myClass = (MyClass) args 
     .getSerializable(TAG_MY_CLASS); 
+0

nel tuo codice cosa è 'TAG_TO_FRAGMENT' – kosala

+0

Sei il migliore.Grazie – kosala

+1

@Sameera Di solito metto una stringa con la mia classe di frammenti, cioè se ho classe MyFragmentIMGoingTo.java poi il mio TAG_TO_FRAGMENT =" MyFragmentIMGoingTo "; –

11

completo del codice dei dati che passano tramite frammento di frammentare

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle(); 
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
       bundle.putString("key","value"); // use as per your need 
       fragment.setArguments(bundle); 
       fragmentTransaction.addToBackStack(null); 
       fragmentTransaction.replace(viewID,fragment); 
       fragmentTransaction.commit(); 

In classe personalizzato di frammentazione

Bundle mBundle = new Bundle(); 
mBundle = getArguments(); 
mBundle.getString(key); // key must be same which was given in first fragment 
+0

dove ottenere viewID? – Hoo

+0

@Hoo: per favore specifica la tua domanda cosa vuoi chiedere –

+0

puoi aiutarmi? https://stackoverflow.com/questions/32983033/pass-data-to-another-fragment-by-swipe-view-with-tab-android-studio-not-button – Hoo

0

tuo frammento di ingresso

public class SecondFragment extends Fragment { 


    EditText etext; 
    Button btn; 
    String etex; 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.secondfragment, container, false); 
     etext = (EditText) v.findViewById(R.id.editText4); 
     btn = (Button) v.findViewById(R.id.button); 
     btn.setOnClickListener(mClickListener); 
     return v; 
    } 

    View.OnClickListener mClickListener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 


      etex = etext.getText().toString(); 
      FragmentTransaction transection = getFragmentManager().beginTransaction(); 
      Viewfragment mfragment = new Viewfragment(); 
      //using Bundle to send data 
      Bundle bundle = new Bundle(); 
      bundle.putString("textbox", etex); 
      mfragment.setArguments(bundle); //data being send to SecondFragment 
      transection.replace(R.id.frame, mfragment); 
      transection.isAddToBackStackAllowed(); 
      transection.addToBackStack(null); 
      transection.commit(); 

     } 
    }; 



} 

la visualizzazione frammento

public class Viewfragment extends Fragment { 

    TextView txtv; 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.viewfrag,container,false); 
     txtv = (TextView) v.findViewById(R.id.textView4); 
     Bundle bundle=getArguments(); 
     txtv.setText(String.valueOf(bundle.getString("textbox"))); 
     return v; 
    } 


} 
2
  First Fragment Sending String To Next Fragment 
      public class MainActivity extends AppCompatActivity { 
        private Button Add; 
        private EditText edt; 
        FragmentManager fragmentManager; 
        FragClass1 fragClass1; 


        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
         super.onCreate(savedInstanceState); 
         setContentView(R.layout.activity_main); 
         Add= (Button) findViewById(R.id.BtnNext); 
         edt= (EditText) findViewById(R.id.editText); 

         Add.setOnClickListener(new View.OnClickListener() { 
          @Override 
          public void onClick(View v) { 
           fragClass1=new FragClass1(); 
           Bundle bundle=new Bundle(); 

           fragmentManager=getSupportFragmentManager(); 
           fragClass1.setArguments(bundle); 
           bundle.putString("hello",edt.getText().toString()); 
           FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction(); 
           fragmentTransaction.add(R.id.activity_main,fragClass1,""); 
           fragmentTransaction.addToBackStack(null); 
           fragmentTransaction.commit(); 

          } 
         }); 
        } 
       } 
     Next Fragment to fetch the string. 
      public class FragClass1 extends Fragment { 
        EditText showFrag1; 


        @Nullable 
        @Override 
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

         View view=inflater.inflate(R.layout.lay_frag1,null); 
         showFrag1= (EditText) view.findViewById(R.id.edtText); 
         Bundle bundle=getArguments(); 
         String a=getArguments().getString("hello");//Use This or The Below Commented Code 
         showFrag1.setText(a); 
         //showFrag1.setText(String.valueOf(bundle.getString("hello"))); 
         return view; 
        } 
       } 
    I used Frame Layout easy to use. 
    Don't Forget to Add Background color or else fragment will overlap. 
This is for First Fragment. 
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:id="@+id/activity_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:background="@color/colorPrimary" 
     tools:context="com.example.sumedh.fragmentpractice1.MainActivity"> 

     <EditText 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:id="@+id/editText" /> 
     <Button 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      android:id="@+id/BtnNext"/> 
    </FrameLayout> 


Xml for Next Fragment. 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:background="@color/colorAccent" 
    android:layout_height="match_parent"> 
    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/edtText"/> 

</LinearLayout> 
+2

Spiega la tua risposta? codice senza alcuna spiegazione non sarà di grande aiuto – Coder

+0

ho scritto codice in un flusso in modo che possa essere compreso ..... Passare i dati dall'attività principale a FragClass1 con l'uso del pacchetto. –

Problemi correlati