使用代码创建用户界面是一个非常费力的工作。因此,只有在必要时才使用代码来动态生成用户界面。
package com.example.androidtest; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class UICodeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_uicode);//必须注释掉 LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("This is a TextView"); tv.setLayoutParams(params); Button btn = new Button(this); btn.setText("This is a Button"); btn.setLayoutParams(params); layout.addView(tv); layout.addView(btn); LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); this.addContentView(layout, layoutParam); } }
运行效果