Android推荐使用XML文件设置UI界面,而后用Java代码控制逻辑部分,这体现了MVC思想。 android
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件this
设计典范,用一种业务逻辑、数据、界面显示分离的方法。spa
通常思路是这样的,可是有些状况仍是须要用Java代码设置UI界面,好比添加,删除组件等,反正XML设计
文件和Java代码两种方式均可以表示UI界面的,通常状况就能够用XML文件,特殊状况用Java代码表示。code
XML文件表示UI界面xml
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 4 android:orientation="vertical" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" > 7 8 <TextView 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:text="@string/hello" /> 12 13 </LinearLayout>
Java代码表示UI界面
1 layout = new LinearLayout(this); 2 layout.setOrientation(LinearLayout.VERTICAL); 3 4 layout.setLayoutParams(new LayoutParams( 5 LayoutParams.MATCH_PARENT, 6 LayoutParams.MATCH_PARENT)); 7 tView = new TextView(this); 8 tView.setText("Hello,World"); 9 tView.setLayoutParams(new LayoutParams( 10 LayoutParams.MATCH_PARENT, 11 LayoutParams.WRAP_CONTENT)); 12 layout.addView(tView); 13 setContentView(layout);