如何从 EditText 获取值 Android

How to get values from EditText Android

我有一堆 EditText 字段,我正在尝试获取它们的值。但它返回空字符串。这是我的代码:

public class add_product_fragment extends Fragment implements AdapterView.OnItemSelectedListener{

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

        mName = view.findViewById(R.id.productName);
        productName = mName.getText().toString().trim();

        mPrice = view.findViewById(R.id.productPrice);
        productPrice = mPrice.getText().toString().trim();

        mDescription = view.findViewById(R.id.productDescription);
        productDescription = mDescription.getText().toString().trim();

        mQuantity = view.findViewById(R.id.productQuantity);
        productQuantity = mQuantity.getText().toString().trim();

        addToInventory = view.findViewById(R.id.addToInventoryBtn);

        addToInventory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(productName + ", " + productDescription + ", " + productType
                        + ", " + productPrice + ", " + productQuantity);
            }
        });

        return view;
    }

由于 Fragment 原因无法正常工作,还是我遗漏了什么?

只有在 onResume() returns 之后,用户才能与 Activity/Fragment 的 UI 互动。因此,在 FragmentonCreateView() 生命周期方法中使用 yourEditText.getText().toString() 之类的东西将不可避免地导致空字符串。

您应该在用户交互后“检索”EditTexts' 值,这意味着 addToInventoryonClick 侦听器应如下所示:

addToInventory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println(
                mName.getText().toString().trim() + ", " +
                mDescription.getText().toString().trim() + ", " +
                mProductType.getText().toString().trim() + ", " +
                mPrice.getText().toString().trim() + ", " + 
                mQuantity.getText().toString().trim());
        }
    });