【问题标题】:EditView must contain data to further processEditView 必须包含要进一步处理的数据
【发布时间】:2017-05-19 20:19:33
【问题描述】:

我在Fragment 中有一个EdidText 和一个Button。当我单击Button 时,我想检查EditText 是否为空。如果为空我想返回一条错误消息,如果 notEmpty 表示移动到其他 fragments 或其他处理。

我之前搜索过我的问题的解决方案,但大多数情况下我找到了类似的解决方案,

if(textView.getText().toString().trim().equals("")) {
      textView.setError("something");
} else {
     //do something;
}

上面的代码工作正常,但我要问的是,如何在布局中以非编程方式做到这一点。

我想知道这是不是通过布局xml文件实现的。如果可能的话,请给我一个例子。

提前谢谢你。

【问题讨论】:

  • 我认为没有办法通过XML 做到这一点。由于 EditText 值在运行时更改。
  • 没有办法只检查 xml 中的 EditText。是否仍会使用 Java 代码移动到其他片段
  • @M.WaqasPervez 好的,感谢您的热情回复
  • 为什么要在布局中使用它?

标签: android android-fragments layout


【解决方案1】:

您不能在 XML 中设置错误。

您需要在片段的 onCreate 中设置它。这样无论是在 xml 中还是在代码中设置,您都不会看到差异。

您可以编写自己的 EditText 并添加额外的样式属性“error”。之后您需要使用自己的 EditText 并再次在 onCreate 中设置错误。

创建一个新类并像这样从 EditText 扩展它:

public class MyEditText extends EditText {
    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyEditText);
        String error = a.getString(R.styleable.MyEditText_error);
        a.recycle();
        setError(error);
    }
}

在 Attr 中添加:

<declare-styleable name="MyEditText">
    <attr name="error" format="reference|string" />
</declare-styleable>

之后,您将需要始终使用 MyEditText

【讨论】:

    【解决方案2】:

    用这段代码检查一下

    editText.getText().toString().isEmpty()
    

    【讨论】:

    • 请完整阅读我的问题先生/女士,我不想以编程方式进行,而是使用 xml 文件
    • xml里面没办法,xml看不到edittext是否为空。
    猜你喜欢
    • 2013-06-04
    • 1970-01-01
    • 2015-04-01
    • 2017-01-19
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2023-01-30
    相关资源
    最近更新 更多