Java 如何添加其他参数以编程方式创建按钮?
在我的程序中,有2000多个以编程方式创建的按钮。它们看起来像这样:Java 如何添加其他参数以编程方式创建按钮?,java,android,Java,Android,在我的程序中,有2000多个以编程方式创建的按钮。它们看起来像这样: //Parameters of buttons LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); //Create a button based on... if (bla-bla)
//Parameters of buttons
LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//Create a button based on...
if (bla-bla)
{
Button ammian_martsellin_1=new Button(this); ammian_martsellin_1.setText(R.string.ammian_martsellin_1); llPreViewList.addView(ammian_martsellin_1, lParams);
Button ammian_martsellin_2=new Button(this); ammian_martsellin_2.setText(R.string.ammian_martsellin_2); llPreViewList.addView(ammian_martsellin_2, lParams);
}
//And a lot of these groups of buttons.
如何向这些按钮添加其他参数,如重力和文本大小,如“lParams”?您应该能够使用setGravity设置重力。尝试调用ammian_martsellin_1.setGravity(重力值) 您可以在这里查找这些方法
LinearLayout.LayoutParams
主要是只读的,原因是,它主要是从XML资源中获取的AttributeSet
的实现中创建的
您必须对所有视图对象调用setGravity()
。您可以尝试以下操作:
for(int i=0;i<ViewGroup.getChildCount();i++){
if(ViewGroup.getChildAt(i).instanceOf(Button)){
//Do stuff
}
}
for(int i=0;i如果我有很多按钮,是否必须使用所有按钮才能附加新参数?
for(int i=0;i<ViewGroup.getChildCount();i++){
if(ViewGroup.getChildAt(i).instanceOf(Button)){
//Do stuff
}
}