我正在动态创建视图,如下所示
public class DynamicLayoutActivity extends Activity
{
private LinearLayout linear_layout,linear_main;
private Button b1,b2,b3;
private LinearLayout.LayoutParams linear_layout_params,button_parameters;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
linear_main = new LinearLayout(this);
linear_layout = new LinearLayout(this);
linear_layout_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
linear_layout.setOrientation(LinearLayout.VERTICAL);
linear_layout.setGravity(android.view.Gravity.CENTER);
linear_layout.setLayoutParams(linear_layout_params);
linear_layout.setId(3);
// button_parameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
b1=new Button(this);
b1.setText("Button1");
b1.setId(31);
b1.setGravity(android.view.Gravity.CENTER);
// b1.setLayoutParams(button_parameters);
b2=new Button(this);
b2.setText("Button1");
b2.setId(32);
b2.setGravity(android.view.Gravity.CENTER);
// b2.setLayoutParams(button_parameters);
b3=new Button(this);
b3.setText("Button1");
b3.setId(33);
b3.setGravity(android.view.Gravity.CENTER);
// b3.setLayoutParams(button_parameters);
linear_layout.addView(b1);
linear_layout.addView(b2);
linear_layout.addView(b3);
linear_main.addView(linear_layout);
setContentView(linear_main);
}
}
同样,我通过在 xml 文件中声明所有内容来做同样的事情,如下所示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
假设我在上面提到的线性布局中有 100 个按钮,那么这是最好的方法,并且与内存占用和执行时间相关的性能最好
如果您支持某个场景,请向我解释您的观点,为什么该场景是最好的。这样我就可以理解Infalting xml和动态创建视图的使用
提前致谢 ..