我不知道为什么我这么糟糕的挣扎!我有两个通过接口进行通信的片段。回调应该更改一些数据,然后触发一个方法来更改按钮的文本。这是应该更改按钮文本的片段的代码。
public void updateIngredients(final ArrayList<Ingredient> ingredients){
for (Ingredient I : ingredients) {
recipe.addIngredients(I);
}
Log.d(TAG, "Ingredients size: " + ingredients.size());
updateIngredientText();
}
public void updateIngredientText(){
if(recipe.getIngredients() != null) {
Button bIng = (Button) getView().findViewById(R.id.bAddIngredientsToRecipe);
bIng.setText("Ingredients (" + recipe.getIngredients().size() + ")");
}
}
注意我收到了预期结果的日志。但按钮文本根本不会改变。我没有错。
我已尝试在runOnUiThread
中运行此功能,我已尝试在onAttach
和onResume
中运行此功能。按钮ID是正确的,因为我使用bIng
打开另一个片段。
有谁知道为什么这不会改变我的按钮文字?
我认为这与此有关。这是使用需要更改的按钮调用回到片段的方法:
public interface OnIngredientChangedListener {
public void onIngredientAdded(ArrayList<Ingredient> i);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnIngredientChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnIngredientChangedListener");
}
}
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//save button clicked
//notify AddRecipeActivity that ingredients have been added
mCallback.onIngredientAdded(selectedArray);
end();
}
});
private void end() {
//fragment Transaction here
AddRecipe addRecipe = new AddRecipe();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fragment_frame, addRecipe).commit();
}
我认为问题是我正在创建片段的新实例。