以编程方式在XML上创建的复制按钮

问题描述:

我在我的XML上有一个按钮,我想以编程方式创建其他人。有没有简单的方法来复制按钮的属性,而不是一个接一个地复制?以编程方式在XML上创建的复制按钮

我的按钮:

 <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fabImage" 
     android:layout_width="match_parent" 
     android:layout_height="@dimen/fab_height" 
     android:layout_margin="@dimen/activity_margin" 
     android:clickable="true" 
     android:visibility="gone" 
     android:elevation="3dp" 
     app:backgroundTint="@color/white" 
     app:elevation="3dp" 
     app:srcCompat="@drawable/photo" /> 

我想什么情况发生:

@BindView(R.id.fabImage) 
FloatingActionButton fabImage; 

private void addMoreButtons(){ 
FloatingActionButton newFab = fabImage; 
myLayout.addView(newFab); 
} 
+0

同一活动? –

+0

@EliasFazel是 – yasin

+1

您可以根据自己的需要使用'getLayoutParams()'https://developer.android.com/reference/android/view/View.html#getLayoutParams()。其他一切应该在文档的该页面中 – codeMagic

private Button addMoreButtons(){ 
    FloatingActionButton newFab = LayoutInflater 
    .from(context) 
    .inflate(R.layout.button, null); 

    myLayout.addView(newFab); 
    } 

R.layout.button - 根元素必须是按钮(Fab或其他任意键)。

如果您想在相同的活动中重复使用它,只需在不同的位置重用它。一旦你通过查找视图来定义它的实例,你就可以重用。

Button btn = (Button)findViewById(R.id.button); 

现在你可以按钮,这样你喜欢的地方添加这个btn。例如,如果最初它在底部,并且您想先将它添加到顶部,则需要在顶部添加GroupView(RelativeLayout,LinearLayout),然后将该按钮添加到该底部。

linearLayoutTop.addView(btn);