Search code examples
androidandroid-fragmentsmaterial-components-androidandroid-viewbinding

Problem in fragments with view-binding get value Material TexInputEditText


I use fragment with view-binding but there is an interesting thing, I can not get the value in the onViewCreated scope, only in the binding button with click event listener scope.

Fragment.java:

public class Fragment extends Fragment {

    private FragmentBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment, container, false);

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = FragmentBinding.bind(view);

        final String amount1 = binding.formAmountInput.getText().toString();


       binding.formSaveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String amount2 = binding.formAmountInput.getText().toString();
            Toast.makeText(mContext, amount1, Toast.LENGTH_SHORT).show(); // gives nothing, why?
            Toast.makeText(mContext, amount2, Toast.LENGTH_SHORT).show(); // works, shows input data


        }
    });
}

xml part:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/form_amount_layout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:endIconMode="clear_text">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/form__amount_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number|numberDecimal|numberSigned"
      />
  
</com.google.android.material.textfield.TextInputLayout>

                    

Solution

  • final String amount1 = binding.formAmountInput.getText().toString();
    // gives nothing, why?

    Well you are getting the content of the field at that particular point in time. And since you just inflated the view and there is no default text, amount1 is empty.

    If you add android:text="default text" to your TextInputEditText, your amount1 will have something to read.

    amount1 will not automatically update when you edit the text! Hence it only makes sense to call .getText().toString() in the onClick Listener or in a TextWatcher.