我有一個包含2個片段的活動,一個處理所有數據,另一個處理所有數據,只有一個記分板。試圖將數據從一個片段傳遞到另一個片段,但數據不會出現
當一個玩家出局時,Fragment1會要求一個新玩家的名字,而fragment2會使用該記分牌的名字。 我在fragment1中使用靜態方法getPlayerName()並在fragment2中使用它。
該應用程序由一個ListView +自定義ArrayAdapter組合來填充fragment2。
下面是具有所需細節的簡化代碼,它不顯示錯誤但不起作用。我按下,輸入新名稱,但它不出現在記分板中。
嘗試notifydatasetchanged()在各個地方,但似乎這不是解決方案。
FieldFragment.java
public class FieldFragment extends Fragment {
static String playerNames[] = new String[11];
int i = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_field, container, false);
Button out = (Button)rootView.findViewById(R.id.out);
out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayDialog();
}
});
return rootView;
}
public void displayDialog(){
final Dialog nameDialog = new Dialog(getActivity());
nameDialog.setContentView(R.layout.dialog);
Button ok = (Button)nameDialog.findViewById(R.id.ok_button);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText nameET = (EditText)nameDialog.findViewById(R.id.name_edit_text);
playerNames[i] = nameET.getText().toString();
nameDialog.dismiss();
}
});
Button cancel = (Button)nameDialog.findViewById(R.id.cancel_button);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nameDialog.dismiss();
}
});
nameDialog.show();
}
public static String getPlayerName(int playerNumber) {
return playerNames[playerNumber];
}
}
而且ScoreboardFragment:
public class ScoreboardFragment extends Fragment {
public ScoreboardFragment() {
// Required empty public constructor
}
PlayerAdapter playerAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_scoreboard, container, false);
int i=0;
ArrayList<Players> players = new ArrayList<>();
players.add(new Players(getPlayerName(i++),0,0));
players.add(new Players(getPlayerName(i++),0,0));
playerAdapter = new PlayerAdapter(getActivity(), players);
ListView playerList = (ListView)rootView.findViewById(R.id.list_of_players);
playerList.setAdapter(playerAdapter);
return rootView;
}
}
有什麼不好的代碼?
我們知道,如果你需要更多的文件
那麼您是指將數據發送到將從Fragment2調用的Activity中的Activity和getter方法? – Abhijeet
@Abhijeet是的確切 – Mohammad