在我的 Android 应用程序中,我有一个 EditText,当它为空时我想对其执行 setError() 。 EditText 位于名为fragment_amount 的文件中。
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
/>
我将其加载到 fragment 中,如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_amount, null);
}
从最初加载此 EditText 的 fragment 的父 fragment 中(使用上面的 fragment ),我现在想像这样使用 setError:
EditText amountField = (EditText) getView().findViewById(R.id.fragment_amount);
amountField.setError("ERRROROROROR");
不幸的是,我在第一行收到一个 ClassCastException,指出:android.support.v4.app.NoSaveStateFrameLayout 无法转换为 android.widget.EditText
。奇怪的是,在我最初加载此 EditText (AmountFragment.java) 的 fragment 中,它以完全相同的方式加载,没有任何错误。
有人知道如何将此 EditText 作为 EditText 加载到父 fragment 中,以便我可以使用 setError() 方法吗?欢迎所有提示!
最佳答案
试试这个...
您已为您的layout
指定了名称fragment_amount
,并且您已为您的edittext<指定了与
.id
相同的名称
因此,请尝试在 xml 和 java 中更改 edittext
的 id
。(例如,这里我给出了 fragment_amount_edit
)
XML:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_amount_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
/>
JAVA:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_amount, null);
EditText amountField = (EditText) view.findViewById(R.id.fragment_amount_edit);
amountField.setError("ERRROROROROR");
return view;
}
关于java - 如何在 Android 父 fragment 中 findViewById() (获取 ClassCastException)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20468550/