I am appreciating the FloatingActionButton (fab) feature of Android and want to use them in a lot of different places in my project.
Right now, I have something like this, where I have several xml specifications for them, all of them are the same, except the id, icon and the onclick.
<android.support.design.widget.FloatingActionButton
android:id="@+id/fabFoo"
android:onClick="onFabFoo"
android:src="@drawable/ic_foo"
app:backgroundTint="?attr/colorButtonNormal"
app2:elevation="2dp"
app:fabSize="mini"
android:focusable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_margin="2dp"
app:rippleColor="?attr/colorSwitchThumbNormal" />
In the interest of avoiding duplicate code... Is there a way to create the fab entirely programmatically without needing to specify it in xml?
...
Trying out some suggestions... There was no 'setSize' until I upgraded the SDK to current (# 25)
FloatingActionButton fab = new FloatingActionButton(this);
fab.setId(View.generateViewId());
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("DEBUG", "onFabFoo");
}
});
fab.setImageResource(R.drawable.ic_foo);
fab.setElevation(2);
fab.setSize(android.support.design.widget.FloatingActionButton.SIZE_MINI);
fab.setFocusable(true);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
lay.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lay.setMargins(2,2,2,2);
fab.setLayoutParams(lay);
Haven't yet figured out how to set the colors
// app:backgroundTint="?attr/colorButtonNormal"
// app:rippleColor="?attr/colorSwitchThumbNormal"
I see there are methods to set these (setBackgroundTintList and setRippleColor) but I don't see how to set it to the colors I chose in the original xml setting (colorButtonNormal and colorSwitchThumbNormal)
Also, don't know how to attach it to the parent and get it to display...
Okay, I guess I realize now, if you do all this programmatically, then you can't use features like the xml Design view in Android Studio. So it's much harder to work with.