平时多习惯于采用xml文件来添加布局和控件,采用java代码在activity中添加控件也是一种方式,下面简单举两个例子:
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在父控件的基础上添加子控件,作用类似于在xml文件中添加一个控件:
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); } }
xml文件:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="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>
同样可以添加控件的各种属性。效果: