我正在尝试在 fragment 中获取FloatingButton
。
XML:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Demand"
android:id="@+id/frag_demand"
android:layout_gravity="center_horizontal|top"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="65dp"
android:layout_height="65dp"
android:id="@+id/imageButton"
android:background="@drawable/oval"
android:elevation="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="15dp"
android:src="@drawable/ic_menu_add"/>
JAVA:
public class DemandFragment extends Fragment {
MenuItem fav;
ImageButton floatButton;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_demand, container, false);
floatButton = (ImageButton) rootView.findViewById(R.id.imageButton);
floatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG);
}
});
return rootView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
}
logcat 给出:
java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.ImageButton
为什么这不起作用?
帮助
最佳答案
来自给定的异常
java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.ImageButton
很明显,您正在尝试将 ImageView 转换为 ImageButton。在您的情况下,在您的 xml 中您已经定义了带有 id imageButton 的 ImageView
<ImageView
android:layout_width="65dp"
android:layout_height="65dp"
android:id="@+id/imageButton"
android:background="@drawable/oval"
android:elevation="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="20dp"
android:layout_marginRight="15dp"
android:src="@drawable/ic_menu_add"/>
但是在您的 fragment 代码中,您正在执行此操作
floatButton = (ImageButton) rootView.findViewById(R.id.imageButton);
其中 floatButton 是 ImageButton,而不是您在 xml 中定义的 ImageView,因此是异常(exception)。
尝试将 xml 中的 ImageView 更改为 ImageButton 或将 Fragment 代码中的 ImageButton 更改为 ImageView。任何方式都会起作用
关于java - 为什么我的应用程序会因为 ImageView 而崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34773382/