你的位置:首页 > 操作系统

[操作系统]使用java代码添加控件


平时多习惯于采用

1、addContentView

addContentView作用类似于setContentView()来为activity初始化布局:

 1 public class MainActivity extends Activity { 2  3   @Override 4   protected void onCreate(Bundle savedInstanceState) { 5     super.onCreate(savedInstanceState); 6     //setContentView(R.layout.activity_main); 7     TextView tv=new TextView(getApplicationContext()); 8     tv.setText("hello world1"); 9     tv.setBackgroundColor(Color.GRAY);10     tv.setGravity(Gravity.CENTER);11     int x=LayoutParams.MATCH_PARENT;12     int y=LayoutParams.WRAP_CONTENT;13     LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(x,y);14     this.addContentView(tv, params);15     16     17   }18 }

在java代码中添加控件同样可以设置各种属性,如例中setText,setBackgroundColor等。效果:

2、addView

addView在父控件的基础上添加子控件,作用类似于在

public class addViewActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    LinearLayout ll = (LinearLayout) findViewById(R.id.ll);    TextView tv = new TextView(getApplicationContext());    tv.setText("hello world2");    tv.setBackgroundColor(Color.GRAY);    tv.setGravity(Gravity.CENTER);    ll.addView(tv);  }}

1 <LinearLayout ="http://schemas.android.com/apk/res/android"2   ="http://schemas.android.com/tools"3   android:id="@+id/ll"4   android:layout_width="match_parent"5   android:layout_height="wrap_content"6   android:orientation="vertical" >7 8 </LinearLayout>

同样可以添加控件的各种属性。效果: