【问题标题】:Textfield is null even when there is value in it文本字段为空,即使其中有值
【发布时间】:2018-11-14 11:21:51
【问题描述】:

我正在使用片段,必须在它的 Textfield 中。一个是姓名,另一个是电话号码。两者的验证都很好。但是当我敬酒时,它说 null/false。

EditText tPername = (EditText) getView().findViewById(R.id.txtPer);

这是xml

            <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txtPer"
            android:layout_marginBottom="15dp"
            android:background="@drawable/textbox"
            android:layout_gravity="center_horizontal"
            android:inputType="textPersonName"/>

当我 Toast R.id.txtPer 时,它显示为 null。 这是我的java代码

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_add_customer, container, false);
    view.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            doAdd(view);
        }
    });
    return view;
}
public void doAdd(View view) {

    String MobilePattern = "[0-9]{10}";

    EditText tPername = (EditText) getView().findViewById(R.id.txtPer);
    EditText tMobnum = (EditText) getView().findViewById(R.id.txtMob);
if (TextUtils.isEmpty(tPername.getText().toString())) {
    tPername.setError("Please fill this field");
    return;
   } else if (!tMobnum.getText().toString().matches(MobilePattern)) {
        tMobnum.setError("Mobile number must be entered 10 digits only");
        return;
    }

}

【问题讨论】:

  • 显示你的java代码
  • 好的,我将使用 Log。但是 R.id.txtPer 总是说 null
  • 发布你的java代码
  • 你需要发布你的java代码
  • 这是上面的java代码

标签: android android-edittext fragment


【解决方案1】:
type a (EditText tPername = (EditText) getView().findViewById(R.id.txtPer);)

in the onViewCreated

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

EditText tPername = (EditText) getView().findViewById(R.id.txtPer);
    }

【讨论】:

    【解决方案2】:
    String name= tPername.getText().toString();
    

    这解决了我的问题。谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2021-12-18
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多