从回调中设置按钮文本

时间:2014-04-07 19:36:39

标签: java android button android-fragments callback

我不知道为什么我这么糟糕的挣扎!我有两个通过接口进行通信的片段。回调应该更改一些数据,然后触发一个方法来更改按钮的文本。这是应该更改按钮文本的片段的代码。

    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中运行此功能,我已尝试在onAttachonResume中运行此功能。按钮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();
}

我认为问题是我正在创建片段的新实例。

0 个答案:

没有答案