FloatingActionButton无法强制转换为android

时间:2017-07-11 02:40:25

标签: android

我有一个错误" FloatingActionButton无法转换为android"在片段中

这是我的按钮:

<android.support.design.widget.FloatingActionButton
        android:id="@+id/kirim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_menu_upload" />

这是调用按钮的代码

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_chat, container, false);

kirim = (Button) rootView.findViewById(R.id.kirim);

kirim.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            simpan();

        }
    });
return rootView;
}

2 个答案:

答案 0 :(得分:4)

FloatingActionButton无法强制转换为Button。替换此行:

kirim = (Button) rootView.findViewById(R.id.kirim);

使用这行代码:

kirim = (FloatingActionButton) rootView.findViewById(R.id.kirim);

答案 1 :(得分:0)

您将FloatingActionButton投射到Button,这将导致错误,因为FloatingActionButton不会扩展Button。按照错误说明

正确地投射它
kirim = (FloatingActionButton) rootView.findViewById(R.id.kirim);