0leg
0leg

Reputation: 14154

Position FloatingActionButton programmatically in center of CoordinatorLayout

There is a CoordinatorLayout:

<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cl_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.design.widget.CoordinatorLayout>

Question: How does one create and position programmatically a FloatingActionButton in the center of the screen?


Important:: FloatingActionButton is created programmatically only (no need to post the answers where you define it in the XML file).

Upvotes: 0

Views: 3792

Answers (4)

Umut Aksun
Umut Aksun

Reputation: 179

Use this

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
lp.anchorGravity = Gravity.CENTER // or you can add Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL
fab.setLayoutParams(lp);

Upvotes: 0

ND1010_
ND1010_

Reputation: 3841

Try this one :)

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ncrypted.floatingactionbuttoncenter.MainActivity">


<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

public class MainActivity extends AppCompatActivity {
FloatingActionButton fab;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fab = (FloatingActionButton) findViewById(R.id.fab);

    CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
    lp.gravity = Gravity.CENTER;
    fab.setLayoutParams(lp);


}

}

it works in my case :)

Upvotes: 1

0leg
0leg

Reputation: 14154

Since none of the answers worked, after some experiments, the solution is:

((CoordinatorLayout.LayoutParams) fab.getLayoutParams()).gravity = Gravity.CENTER;

Upvotes: 4

Faraz Tariq
Faraz Tariq

Reputation: 54

I think you will find your answer here.

Set layout_anchor at runtime on FloatingActionButton

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);  
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) 
params.setAnchorId(View.NO_ID);
fab.getLayoutParams();
fab.setLayoutParams(params);

Upvotes: -2

Related Questions