今日学习总计

Android UI教程 - Android中的XML与代码

 

您可以使用XML构建布局,然后使用代码填充动态数据。

 

例子

使用ID创建XML中的用户界面

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical">

    <!-- NAME CONTAINER -->

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal">

 

        <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="@string/app_name" />

 

        <TextView

            android:id="@+id/nameValue"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content" />

 

    </LinearLayout>

    <!-- ADDRESS CONTAINER -->

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="vertical">

 

        <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="@string/app_name" />

 

        <TextView

            android:id="@+id/addrValue"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content" />

    </LinearLayout>

 

</LinearLayout>

这些TextViews的实际字符串将来自我们在/ res / values文件夹中的strings.xml文件。下面的代码显示了我们的strings.xml文件可能看起来像。

 

<?xml version="1.0" encoding="utf-8"?>

<resources>

 

    <string name="app_name">www.w3cschool.cn</string>

    <string name="hello_world">www.w3cschool.cn</string>

    <string name="action_settings">Settings</string>

 

</resources>

 

在运行时参考资源中的控件

 

// ww  w . j av a2 s.  c  o  m

package com.java2s.app;

 

import android.app.Activity;

import android.os.Bundle;

import android.widget.TextView;

public class MainActivity extends Activity

{

    @Override

    public void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        TextView nameValue = (TextView)findViewById(R.id.nameValue);

        nameValue.setText("Main");

        TextView addrValue = (TextView)findViewById(R.id.addrValue);

        addrValue.setText("Street");

 

    }

}

 

posted @ 2021-05-23 20:08  禁小呆  阅读(20)  评论(0)    收藏  举报