Create FloatingActionButton programmatically (without xml)
There are two I can think of
Using java only
Create a FloatingActionButton
directly in code like
public FloatingActionButton getFab(Context context) {
FloatingActionButton fab = new FloatingActionButton(context);
...
return fab;
}
Inflating the layout
public FloatingActionButton getFab(Context context, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
return (FloatingActionButton) inflater.inflate(R.layout.myfab, parent, false);
}
More about inflater
Edit:
You can use setBackgroundTintList
and setRippleColor
to set the 2 attributes.
And to attach it to parent you do
layout.addView(v);
But I feel using LayoutInflater
is better because it does both tasks of generating a FloatingActionButton and attaching it to its parent.
inflater.inflate(R.layout.myfab, layout, true)
We can achieve to create a Floating action button in Programmatically
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/my_relative_layout">
</RelativeLayout>
This is the main xml layout file Not inside this parent layout file we can crate floating action button with the following code in class file.
public class MyClass extends AppCompatActivity{
RelativeLayout relativeLayout;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
relativeLayout = (RelativeLayout) findViewByID(R.id.my_relative_layout);
FloatingActionButton fab = new FloatingActionButton(getContext());
fab.setId(R.id.fab_location_main);
fab.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
));
relativeLayout.addView(fab);
}
}
Now