Android的常見控件的核心是兩個類:
android.view.View
android.view.ViewGroup
View
類表示通用的 View
對象。Android中的常用控件最終會擴(kuò)展View
類。
ViewGroup
是一個視圖,它包含其他視圖。 ViewGroup
是布局類列表的基類。
Android使用布局的概念來管理如何在容器視圖內(nèi)布置控件。
你可以從多種方法中選擇一種在Android中構(gòu)建UI。
每個 View
和 ViewGroup
都有一組通用屬性。
layout_weight
和 layout_gravity
屬性僅在View位于LinearLayout
或 TableLayout
中時才適用。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
例如,<TextView>
元素的寬度使用fill_parent
常量填充其父對象的整個寬度。
其高度由 wrap_content
常量指示,這意味著它的高度是其內(nèi)容的高度(在這種情況下,其中包含的文本)。
如果你不想讓<TextView>
視圖占據(jù)整行,你可以將其layout_width
屬性設(shè)置為 wrap_content
,如下所示:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" />
上述代碼將設(shè)置視圖的寬度等于其中包含的文本的寬度。
將activity連接到UI(main_layout_xml_file.xml
)的代碼是 setContentView()
方法:
package cn.w3cschool.app; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
將以下代碼以粗體添加到 res/layout/
,在你的主xml文件中進(jìn)行布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="This is my first Android Application!" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="And this is a clickable button!" /> </LinearLayout>
R.layout.main
是指位于res/layout
文件夾中的main.xml文件。
當(dāng)你向 res/layout
文件夾中添加其他XML文件時,文件名將自動在 R.java
文件中生成。
onCreate()
方法是在加載activity時觸發(fā)的許多方法之一。
更多建議: