如何从Android的EditText中获取值

3

我有一堆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还是我漏了什么?

1个回答

1
用户只能在onResume()返回后与Activity/Fragment的UI进行交互。因此,在FragmentonCreateView()生命周期方法中使用yourEditText.getText().toString()之类的内容将不可避免地导致空字符串。
您应该在用户交互后“检索”EditText的值,这意味着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());
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接