2017-04-14 23 views
0
中心

有一個CoordinatorLayout位置FloatingActionButton編程方式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> 

問:一個人如何編程方式創建和位置在屏幕的中心FloatingActionButton


重要:FloatingActionButton創建編程僅(無需張貼在那裏你在XML文件中定義它的答案)。

回答

2

由於沒有答案的工作,一些實驗後,解決的辦法是:

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

使用此

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); 
-2

我想你會在這裏找到答案。

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); 
0

試試這個:)

<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); 


} 

}

它的作品在我的情況:)

相關問題