How to put FloatingActionButton to Fragment?
You have added the floating action button in your activity_ownerhome.xml and you are initializing it in ownerhomeFragment.java.
So add your FloatingActionButton in fragmentownerhome.xml itself like this
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.kun.carkila.ownerhome"
tools:showIn="@layout/activity_ownerhome">
<ListView
android:layout_width="match_parent"
android:layout_height="450sp"
android:id="@+id/lvOnwer"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="24dp"
android:textSize="30sp"
android:textColor="@color/colorPrimaryDark"
android:id="@+id/tvUser" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/plus" />
</RelativeLayout>
and remove the FloatingActionButton from your activity_ownerhome.xml file.
The cause of the crash is because your FAB xml code is in the "Activity layout", it is supposed to be in the "fragment layout" file
This is how i use FAB in a fragment
In my fragment layout file:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
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_dialog_email" />
In my fragment class file:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
return view;
}
And it works...
NOTE:
when i included android:backgroundTint="@android:color/transparent"
the application crashed and gave the error :
Binary XML file line #14: Error inflating class android.support.design.widget.FloatingActionButton
Hope this helps.