在实际开发中可能我们会遇到一个activity的界面是不固定的,随时可能变化,这时候我们就可以利用编码来制作界面了
在开始之前我们要介绍一个非常重要的类 ViewGroup.LayoutParams,这个类用来设置该布局或者该控件的大小(就和我们在布局文件中定义android:layout_width="fill_parent" android:layout_height="fill_parent"一样)。
具体代码如下:
.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
那么我们接下来讲讲代码编写界面的具体步骤:
(1) 创建一个控件或者布局对象:
LinearLayout linearLayout = new LinearLayout(this);
TextView textView = new TextView(this);
(2)设置控件或者布局对象的大小
LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
(3)应用:布局对象和空间对象的应用是有区别的,
布局对象的使用(应用)
setContentView(linearLayout, layoutParams);
控件对象的应用:(因为控件是要被加载到布局对象里面去的)
TextView textView = new TextView(this);
textView.setText(R.string.hello);
ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.addView(textView, textViewParams);
(4)给控件或者布局添加属性
比如给布局对象添加方向:
linearLayout.setOrientation(LinearLayout.VERTICAL);
给textview控件对象添加text
textView.setText(R.string.hello);
完整代码如下。和上面不同的是包括不变的部分和需要改变的部分,不变的部分写在xml文件里面,变得部分写在java代码里面
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText(R.string.hello);
ViewGroup.LayoutParams textViewParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.addView(textView, textViewParams);
View partView = getPartUI();
linearLayout.addView(partView);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(linearLayout, layoutParams);
}
private View getPartUI(){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.part, null);//R.layout.part,是不变的部分
}