我有一个XML布局,只有一个TextView
现在我想在我的java文件中添加50个动态添加的按钮!
是否可以通过java代码向XML文件添加属性? 或者一个活动一次可以有2个布局?
例如,
public class Options extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
Button but=new Button(this);
but.setText("Wassup");
// How do I add this button to the layout ?
}
}
答案 0 :(得分:3)
是否可以通过java代码向XML文件添加属性?
不,但您可以像Views
一样向Layouts
和setText()
添加属性。编译后无法更改resource
个文件。
或者一个活动一次可以有2个布局吗?
简单的答案是否定的,但您可以inflate
另一个布局并将其添加到当前布局。
您可以执行的有关添加Button
对您的根layout
进行通知,并使用Buttons
将addView()
添加到其中。像
Layoutinflater inflater = (LayoutInflater) getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout_file);
Button but=new Button(this);
but.setText("Wassup");
// How do I add this button to the layout ?
ll.addView(but);
或者,如果您要将其添加到当前文件中的layout
,则可以使用findViewById()
并使用addView()
将Buttons
添加到。{ / p>
答案 1 :(得分:1)
考虑到你有一个xml布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/mainlayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
在setContentView(R.layout.options)之后的java代码中;你可以做到以下几点:
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.mainlayout);
Button button=new Button(this);
linearLayout.addView(button);
现在,您可以在线性布局中添加任意多个按钮,如上所示。
答案 2 :(得分:0)
是的,这是可能的。 setContentView(R.layout.options);
使用findViewById
()获取按钮容器后。您将引用LinearLayout,RelativeLayout或其他内容。之后使用Layout inflater并以编程方式添加其他布局或组件。
希望它有所帮助!
答案 3 :(得分:0)
只需使用layout.addView(),其中layout是通过调用findViewById(R.id.layoutId)获得的ViewGroup