视图绑定片段中的问题获取值 Material TexInputEditText

Problem in fragments with view-binding get value Material TexInputEditText

我在视图绑定中使用片段,但有一件有趣的事情,我无法在 onViewCreated 范围内获取值,只能在具有点击事件侦听器范围的绑定按钮中获取值。

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 部分:

<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>

                    

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

您正在获取该字段在特定时间点的内容。由于您只是扩充了视图并且没有默认文本,因此 amount1 是空的。

如果您将 android:text="default text" 添加到您的 TextInputEditText,您的 amount1 将有内容可读。

amount1编辑文字时不会自动更新!因此,只有在 onClick 侦听器或 TextWatcher 中调用 .getText().toString() 才有意义。