2014-01-14 204 views
0

我有一個名爲AddPlayerFragment的片段,它需要一些字符串。我是這樣做的..從一個片段發送值到另一個片段

public Dialog onCreateDialog(Bundle savedInstanceState) { 

    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); 
    alert.setTitle("Add Player"); 

    // Set an EditText view to get user input 
    final EditText input = new EditText(getActivity()); 
    alert.setView(input); 

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int whichButton) { 
      String value = input.getText().toString(); 

      dialog.dismiss(); 

      return; 
     } 
    }); 

    alert.setNegativeButton("Cancel", 
      new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        // TODO Auto-generated method stub 
        return; 
       } 
      }); 
    return alert.show(); 
}} 

我想從變量值該字符串值讓我叫Scorecard_Fragment另一個片段。我絕對是Android開發的初學者。任何建議?我有一些線索可以通過Bundle或Intent做到,但不知道怎麼做!

+0

解決了這個問題.. – muktoshuvro

+0

Bundle bundle = new Bundle(); bundle.putString(「message」,value); MyBundles.scorePLayer = value; ((Scorecard_Fragment)MainActivity.getFragment())。scorePlayer(value); – muktoshuvro

回答

2

傳輸數據,如這個 -

Bundle bundle = new Bundle(); 
    bundle.putString("message", value); 
    Scorecard_FragmentfragInfo = new Scorecard_Fragment(); 
    fragInfo.setArguments(bundle); 
    transaction.replace(R.id.fragment_single, fragInfo); 
    transaction.commit(); 
0

容易...使用sharedpreferences?

final SharedPreferences prefs = getSharedPreferences("my_prefs, 0); 

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int whichButton) { 
     String value = input.getText().toString(); 

     prefs.edit().putString("myvalue", value).commit(); 

     dialog.dismiss(); 

     return; 
    } 
}); 

在您的片段你可以檢索然後將它與您的方法如下:

final SharedPreferences prefs = getSharedPreferences("my_prefs", 0); 
String myPreviousValue = prefs.getString("myvalue", ""); 

或者去捆綁包與張貼阿米特的解決方案。在我看來,SharedPreferences更好,因爲您可以輕鬆地將它們放在任何地方,以便在沒有硬件代碼的情況下進一步使用,方法是將捆綁包轉移到您需要值的每個片段中。

0

創建您Scorecard_Fragment公共變量:

public String variable; 

然後在AddPlayerFragment:

String value = input.getText().toString(); 
Scorecard_Fragment fragInfo = new Scorecard_Fragment(); 
fragInfo.variable = value; 
transaction.replace(R.id.fragment_layout, fragInfo); 
transaction.commit(); 
0

解決了這個問題.. AddplayerFragment

Bundle bundle = new Bundle(); 
bundle.putString("message", value); 
MyBundles.scorePLayer = value; 
((Scorecard_Fragment) MainActivity.getFragment()).scorePlayer(value); 

通過這個類

public class MyBundles { 
public static String scorePLayer = ""; 
} 
相關問題