我們在 Andriod學習筆記(三):Andriod程序框架 ,中對main.xml文件進行了初步的了解,這本次,我們將初步學習Activity和main.xml的關系。
雖然我們可以使用java code來編寫UI,但是更通用的方式是使用XML-based Layout文件,它用于描述widget和container之間的關系。這使得我們可以方便閱讀和是UI設計獨立,也使得一些IDE工具可以提供直觀的GUI。
1、修訂main.xml
<!-- 線性布局,從上到下,方向由orientation的方向確定 fill_parent即填充其父控件,這里就是全屏。-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- 如果在Java source code中對此widget有由代碼,需提供id, andriod:id="@+id/<name>" ,在R.java上有對應的代碼,對應為 R.id.<name> , 在這個例子中我們在R.java中查到:R.id.myTextView=0x7f040000,我們可以通過name,在程序中對應這個空間。-->
<TextView
android:id="@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<!-- 增加一個新的控件button,Button:是widget的名字,如果我們定義我們自己的widget(是andriod.view.View的子類),我們需要給出完整的包路徑,例如com.wei.andriod.MyWidget)。-->
<Button
android:id="@+id/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
2、在源代碼中,通過我們在xml中定義的名字來獲取該實例
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//R.layout.main,就是在R.java中的R類定義的layout中main,格式為:R.layout.<layout的xml文件名字>,就是對應的res/layout/main.xml文件。
setContentView( R.layout.main );
TextView myTextView = (TextView) findViewById (R.id.myTextView);
myTextView.setText("我的Activity");
Button myButton = (Button) findViewById (R.id.myButton);
myButton.setText("我的按鈕");
}
3、運行,如圖所示。
相關鏈接: 我的Android開發相關文章
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
