1. 程式人生 > 其它 >安卓基礎介面設計

安卓基礎介面設計

目錄

1、控制UI介面

安卓提供了四種控制UI介面的方法

1.1、使用xml佈局檔案控制UI介面

使用xml佈局檔案控制UI介面主要分為以下兩個步驟:

  1. 在android應用的res/layout目錄下編寫xml佈局檔案。建立後,R.java會自動收錄該佈局檔案資源。
  2. 在Acitity中使用以下Java程式碼顯示xml佈局檔案內容
setContentView(R.layout.main);

其中main是佈局檔案的檔名

例1.建立Adroid專案,使用xml佈局檔案實現開始介面

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title"
        style="@style/text"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/startButton"
        android:layout_gravity="center_vertical|center_horizontal"
        style="@style/text"
        android:text="@string/start"/>

</FrameLayout>

style屬性可以設定樣式

android:layout_gravity="center_vertical|center_horizontal"可以設定元件在幀佈局中居中顯示

在res/values目錄下的string.xml檔案中新增一個定義一個開始按鈕的常量

<resources>
    <string name="title">使用佈局檔案控制UI介面</string>
    <string name="start">單擊進入android...</string>
</resources>

為了改變窗體中文字的大小,需要為TextView元件新增syle屬性,用於指定應用的樣式。具體的樣式需要在res\values目錄中建立的樣式檔案中指定。在本例項中,建立一個名稱為styles.xml的樣式檔案,並在該檔案中建立一個名稱為text的樣式,用於指定文字的大小和顏色。styles..xml檔案的具體程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="text">
        <item name="android:textSize">24px</item>
        <item name="android:textColor">#111111</item>
    </style>
</resources>

在主活動中,用以下內容應用佈局檔案

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

1.2、在程式碼中控制UI介面

在程式碼中控制UI介面可以分為以下3個關鍵步驟。

  1. 建立佈局管理器,可以是幀佈局管理器、表格佈局管理器、線性佈局管理器和相對佈局管理器等,並且設
    置佈局管理器的屬性。例如,為佈局管理器設定背景圖片等。
  2. 建立具體的元件,可以是TextView、Image View、EditText和Button等任何Android提供的元件,並且
    設定元件的佈局和各種屬性。
  3. 將建立的具體元件新增到佈局管理器中。
package com.example.myapplication;

import ...

public class MainActivity extends AppCompatActivity {

    public TextView textView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //新增幀佈局管理器
        FrameLayout frameLayout = new FrameLayout(this);
        frameLayout.setBackground(this.getResources().getDrawable(R.drawable.abc_vector_test));
        setContentView(frameLayout);
        //新增TextView元件
        TextView textView = new TextView(this);
        textView.setText("在程式碼中控制UI介面");
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
        textView.setTextColor(Color.rgb(1, 1, 1));
        frameLayout.addView(textView);
        //例項化元件textView1
        textView1 = new TextView(this);
        textView1.setText("點選進入android...");
        textView1.setTextSize(TypedValue.COMPLEX_UNIT_PX, 24);
        textView1.setTextColor(Color.rgb(1, 1, 1));
        //設定儲存佈局引數的物件
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; //設定居中顯示
        textView1.setLayoutParams(layoutParams);
        //為textView1元件設定點選監聽事件
        textView1.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(MainActivity.this).setTitle("系統提示")
                        .setMessage("Android是一個豐富多彩智慧的世界,確定要進入嗎?")
                        .setPositiveButton("確定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Log.i("Android", "進入");
                                    }
                                }).setNegativeButton("退出",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.i("Android", "退出");
                                finish();
                            }
                        }).show();

            }
        });
        frameLayout.addView(textView1);
    }
}

說明:完全通過程式碼控制UI介面雖然比較靈活,但是其開發過程比較煩瑣,而且不利於高層次的解耦,因此不推薦採用這種方式控制UI介面。

1.3、xml佈局檔案和程式碼混合控制UI介面

使用XML和Jva程式碼混合控制UI介面,習慣上把變化小、行為比較固定的元件放在XML佈局檔案中,把變化較多、行為控制比較複雜的元件交給Java程式碼來管理。下面通過一個具體的例項來演示如何使用XML和Java程式碼混合控制UI介面。

例l,3建立Android專案,通過XML和Java程式碼在窗體中橫向並列顯示4張圖片。
(I)修改新建專案的res\layout目錄下的佈局檔案main.xml,將預設建立的元件刪除,然後將預設建立的線性佈局的orientation屬性值設定為horizontal(水平),並且為該線性佈局設定背景以及id屬性。修改後的代
碼如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

</LinearLayout>

(2)在MainActivity中,宣告img和imagePath兩個成員變數,其中,img是一個ImageView型別的一維陣列用於儲存mageView元件;imagePath是一個int型的一維陣列,用於儲存要訪問的圖片資源。關鍵程式碼如下:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import ...

public class MainActivity extends AppCompatActivity {

    private ImageView[] imageViews = new ImageView[12];
    private int[] imagePath = new int[]{
            R.drawable.imge01, R.drawable.imag02, R.drawable.imag03};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.la);
        for (int i = 0; i < imagePath.length; i++) {
            imageViews[i] = new ImageView(this);
            imageViews[i].setImageResource(imagePath[i]);
            imageViews[i].setPadding(5, 5, 5, 5);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(253, 148);
            imageViews[i].setLayoutParams(params);
            layout.addView(imageViews[i]);
        }
    }
}

1.4、開發自定義的View

在Android中,所有的UI介面都是由View類和ViewGroup類及其子類組合而成的。其中,View類是所有UI元件的基類,而ViewGroup類是容納這些UI元件的容器,其本身也是View類的子類。在ViewGroup類中,除了可以包含普通的View類外,還可以再次包含ViewGroup類。

開發自定義的View元件大致分為以下3個步驟:

  1. 建立一個繼承android.view.View類的View類,並且重寫構造方法。

  2. 根據需要重寫相應的方法。

  3. 在專案的活動中,建立並例項化自定義Viw類,並將其新增到佈局管理器中。

下面通過一個具體的例項來演示如何開發自定義的View類。

自定義View元件實現跟隨手指移動的圖片

建立活動,在佈局檔案中新增幀佈局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/myframe"
    android:background="@drawable/background01">
</FrameLayout>

建立Java檔案,繼承自View,重寫其構造方法

package com.example.rabbitproject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class RabbitView extends View {
    //用來記錄圖片的座標
    float x;
    float y;
    public RabbitView(Context context) {
        super(context);
        //為座標新增初始值
        x = 400;
        y = 400;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.imag01);//根據圖片生產點陣圖物件
        canvas.drawBitmap(bitmap, x, y, paint);//繪製圖片
        if (bitmap.isRecycled()){//判斷是否回收,若沒有回收則強制回收
            bitmap.recycle();
        }
    }
}

建立並例項化自定義的元件,新增到佈局中

package com.example.rabbitproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.myframe);
        RabbitView rabbitView = new RabbitView(this);
        rabbitView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                rabbitView.x = motionEvent.getX();
                rabbitView.y = motionEvent.getY();
                rabbitView.invalidate();
                return true;
            }
        });
        frameLayout.addView(rabbitView);
    }
}

2、佈局管理器

Android中提供了線性佈局管理器(LinearLayout)、表格佈局管理器(TableLayout)、幀佈局管理器(FrameLayout)、相對佈局管理器(RelativeLayout)和絕對佈局管理器(AbsoluteLayout),對應於這S種佈局管理器,Android提供了S種佈局方式,其中,絕對佈局在Android2.0中被標記為已過期,可以使用幀佈局或相對佈局替代

2.1、線性佈局

線性佈局是將放入其中的元件按照垂直或水平方向來佈局,也就是控制放入其中的元件橫向或縱向排列。線上性
佈局中,每一行(針對垂直排列)或每一列(針對水平排列)中只能放一個元件,並且Android的線性佈局不會換行,當元件排列到窗體的邊緣後,後面的元件將不會被顯示出來

說明:線上性佈局中,排列方式由android:orientation屬性來控制,對齊方式由android:gravity屬性來控制。

在Android中,可以在XML佈局檔案中定義線性佈局管理器,也可以使用Java程式碼來建立(推薦使用前者)
在XML佈局檔案中定義線性佈局管理器時,需要使用標記,其基本的語法格式如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center_horizontal"
    android:id="@+id/linearLout"
    android:background="@color/white">

</LinearLayout>

線上性佈局管理器中,常用的屬性包括android:orientation、android:gravity、android:layout width、
android:layout height、.android:id和android:background。其中,前兩個屬性是線性佈局管理器支援的屬性,後面4個是android.view.View和android.view.ViewGroup支援的屬性,下面進行詳細介紹。

2.1.1、android:orientation

android:orientation屬性用於設定佈局管理器內元件的排列方式,其可選值為horizontal和vertical,預設值為vertical。其中,horizontal表示水平排列;vertical表示垂直排列。

2.1.2、android:gravity

android:gravity屬性用於設定佈局管理器內元件的對齊方式,其可選值包括top、bottom、left、right、center vertical、fill_vertical、center_horizontal、fill horizontal、center、fill、clip vertical和clip_horizontal。這些屬性值也可以同時指定,各屬性值之間用豎線隔開。例如,要指定元件靠右下角對齊,可以使用屬性值right bottom。

2.1.3、android:layout_width

android:layout_width屬性用於設定元件的基本寬度,其可選值包括fill parent、match_parent和wrap_content。其中,fill_parent表示該元件的寬度與父容器的寬度相同;match_paren與fill parent的作用完全相同,從Android2.2開始推薦使用;wrap content:表示該元件的寬度恰好能包裹它的內容。

2.1.4、android:layout_height

android:layout_height屬性用於設定元件的基本高度,其可選值包括fill parent、match_parent和wrap_content。其中,fill parent表示該元件的高度與父容器的高度相同;match paren與fill parent的作用完全相同,從Android2.2開始推薦使用;wrap content表示該元件的高度恰好能包裹它的內容。

2.1.5、android:id

android:id屬性用於為當前元件指定一個id屬性,在Java程式碼中可以應用該屬性單獨引用這個元件。為元件指定id屬性後,在R.java檔案中,會自動派生一個對應的屬性,在Java程式碼中,可以通過findViewByldO)方法來獲取它。

2.1.6、android:background

android:background屬性用於為元件設定背景,可以是背景圖片,也可以是背景顏色。用下以的程式碼進行設定:

android:background="@drawable/background"

如果想指定背景顏色,可以使用顏色值。例如,要想指定背景顏色為白色,可以使用下面的程式碼:

android:background="#FFFFFFFF"

2.2、表格佈局

表格佈局與常見的表格類似,以行、列的形式來管理放入其中的UI元件。表格佈局使用標記定義,在表格佈局中,可以新增多個標記,每個標記佔用一行。由於標記也是容器,所以還可在該標記中新增其他元件,每新增一個元件,表格就會增加一列。在表格佈局中,列可以被隱藏,也可以被設定為伸展的,從而填充可利用的螢幕空間,還可以設定為強制收縮,直到表格匹配螢幕大小。

TableLayout繼承了LinearLayout,因此它完全支援LinearLayout支援的全部XML屬性,此外,TableLayout
還支援如圖所示的XML屬性。

屬性 描述
Android:collapseColumns 設定需要被隱藏的列的列序號(序號從0開始),多個列序號之間用逗號“,”分割
android:shrinkColumns 設定允許被收縮的列的列序號
android:strethColumn 設定允許被拉伸的列序號

實現使用者登入介面:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tableLyout1"
    android:gravity="center_vertical"
    android:stretchColumns="0,3">
    <!--第一行-->
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView/>
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/textView1"
            android:text="使用者名稱:"
            android:textSize="24px"/>
        <EditText
            android:id="@+id/editText1"
            android:textSize="24px"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:minWidth="200px"/>
        <TextView/>
    </TableRow>
    <!--第二行-->
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView/>
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/textView2"
            android:text="密 碼:"
            android:textSize="24px"/>
        <EditText
            android:id="@+id/editText2"
            android:textSize="24px"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:minWidth="200px"/>
        <TextView/>
    </TableRow>
    <!--第三行-->
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView/>
    <Button
        android:text="登入"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:text="註冊"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
  </TableLayout>

說明:在本例項中,添加了6個TextView元件,並且設定對應列允許拉伸,這是為了讓使用者登入表單在水平方向上居中顯示而設定的。

2.3、幀佈局

在幀佈局管理器中,每加入一個元件,都將建立一個空白的區域,通常稱為一幀,這些幀都會根據gravity屬性執行自動對齊。預設情況下,幀佈局從螢幕的左上角(0,0)座標點開始佈局,多個元件層疊排序,後面的元件覆蓋前面的元件。

顯示疊層的正方形

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frameLayout1"
    android:foreground="@android:color/black"
    android:foregroundGravity="bottom|right">
    <!--新增居中顯示的紅色背景的TextView,將顯示在最下層-->
    <TextView
        android:text="紅色背景的TextView"
        android:layout_width="400px"
        android:layout_height="400px"
        android:layout_gravity="center"
        android:background="#FFFF0000"
        android:id="@+id/textView1"/>
    <!--新增居中顯示的橙色背景的TextView,將顯示在中間層-->
        <TextView
            android:text="橙色背景的TextView"
            android:layout_width="300px"
            android:layout_height="300px"
            android:id="@+id/textView2"
            android:background="#FFFF6600"
            android:layout_gravity="center"/>
    <!--新增居中顯示的黃色背景的TextView,將顯示在最上層-->
    <TextView
        android:text="黃色背景的TextView"
        android:layout_width="200px"
        android:layout_height="200px"
        android:id="@+id/textView3"
        android:background="#FFFFEE00"
        android:layout_gravity="center"/>
</FrameLayout>

2.4、相對佈局

相對佈局是指按照元件之間的相對位置來進行佈局,如某個元件在另一個元件的左邊、右邊、上方或下方等。在Android中,可以在XML佈局檔案中定義相對佈局管理器,也可以使用Java程式碼來建立。推薦使用前者。在XML佈局檔案中定義相對佈局管理器可以使用標記,其基本的語法格式如下:

在相對佈局管理器中,只有上面介紹的兩個屬性是不夠的,為了更好地控制該佈局管理器中各子元件的佈局分佈RelativeLayout提供了一個內部類RelativeLayout..LayoutParams,通過該類提供的大量XML屬性,可以很好地控制相對佈局管理器中各元件的分佈方式。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relativeLayout1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="發現有widget的新版本,要現在就更新嗎?"
        android:id="@+id/textView1"
        android:textSize="55px"
        android:layout_centerHorizontal="true"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="現在更新"
        android:id="@+id/button1"
        android:layout_below="@id/textView1"
        android:layout_toLeftOf="@id/button2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:layout_below="@id/textView1"
        android:layout_alignRight="@id/textView1"
        android:text="以後再說"/>
</RelativeLayout>

3、範例

範例1:使用表格佈局與線性佈局實現分類工具欄

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tableLayout1"
    android:padding="10px">
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="#edff1249"
            android:layout_weight="1"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/text1"
                android:text="框1"
                android:textSize="150px"
                android:gravity="center"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="wrap_content"
            android:background="#ffff1877"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:id="@+id/text2"
                android:text="框2"
                android:textSize="150px"
                android:gravity="center"/>
        </LinearLayout>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:id="@+id/linearLayout3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/purple_500"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/black"
                />
        </LinearLayout>
        <LinearLayout
            android:id="@+id/linearLayout5"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#ffff0000"/>
        </LinearLayout>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow3"
        android:background="#FFFFEE00"
        android:layout_width="match_parent"
        android:layout_weight="1">
        <LinearLayout
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:background="@color/black"/>
        <LinearLayout
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:background="@color/material_on_background_emphasis_medium"/>
    </TableRow>
</TableLayout>

4、基本元件

4.1、文字框TextView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:autoLink="email"
        android:textSize="50pt"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="209dp"
        android:background="@drawable/mmexport1647693561983"
        android:text="帶圖片的TextView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:text="多行文字:從前有一個老人,他給我們帶了很多蘋果"
        android:textSize="20px"
        android:width="300px"
        android:textColor="#0f0"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView3"
        android:text="單行文字:從前有一個老人,他給我們帶了很多蘋果"
        android:textSize="20px"
        android:width="300px"
        android:textColor="#f00"
        android:singleLine="true"/>
</LinearLayout>

4.2、文字編輯框EditView

在Android中,編輯框使用EditText表示,用於在螢幕上顯示文字輸入框,這與Java中的文字框元件功能類似。需要說明的是,Android中的編輯框元件可以輸入單行文字,也可以輸入多行文字,還可以輸入指定格式的文字(如密碼、電話號碼、E-mail地址等)。
在Android中,可以使用兩種方法向螢幕中新增編輯框:一種是通過在XML佈局檔案中使用標記新增;另一種是在Java檔案中,通過new關鍵字建立。

在螢幕中新增編輯框後,還需要獲取編輯框中輸入的內容,這可以通過編輯框元件提供的getText(0方法實現。使用該方法時,先要獲取到編輯框元件,然後再呼叫getText(0方法。例如,要獲取佈局檔案中新增的id屬性為login的編輯框的內容,可以通過以下程式碼實現:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tableLayout1"
    android:background="#2FFFFB00">
    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tabMode1">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="會員暱稱:"
            android:textSize="20dp"
            android:inputType="textPersonName"
            android:id="@+id/textView1"
            android:height="50px"/>
        <EditText
            android:id="@+id/nickname"
            android:layout_width="500px"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:hint="請輸入會員暱稱"/>
    </TableRow>
    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tabMode2">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密        碼:"
            android:textSize="20dp"
            android:inputType="textVisiblePassword"
            android:id="@+id/textView2"
            android:height="50px"/>
        <EditText
            android:id="@+id/password_toggle"
            android:layout_width="500px"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:inputType="textPassword"
            android:hint="請輸入密碼"/>
    </TableRow>
    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tabMode3">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="確認密碼:"
            android:textSize="20dp"
            android:inputType="textVisiblePassword"
            android:id="@+id/textView3"
            android:height="50px"/>
        <EditText
            android:id="@+id/password_toggle1"
            android:layout_width="500px"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:inputType="textPassword"
            android:hint="請再次輸入密碼"/>
    </TableRow>
    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tabMode4">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="   email    :"
            android:textSize="20dp"
            android:inputType="textVisiblePassword"
            android:id="@+id/textView4"
            android:height="50px"/>
        <EditText
            android:id="@+id/email"
            android:layout_width="500px"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:inputType="textPassword"
            android:hint="請輸入Email"/>
    </TableRow>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:background="#19FF00FF"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="註冊"
            android:id="@+id/button1"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  "/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="重置"
            android:id="@+id/button2"/>
    </LinearLayout>
</TableLayout>

package com.example.edittextproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText edittext1 = (EditText)findViewById(R.id.nickname);
                String name = edittext1.getText().toString();
                EditText editText2 = (EditText) findViewById(R.id.password_toggle);
                String password = editText2.getText().toString();
                EditText editText3 = (EditText) findViewById(R.id.password_toggle1);
                String password2 = editText3.getText().toString();
                EditText editText4 = (EditText) findViewById(R.id.email);
                String email = editText4.getText().toString();
                Log.i("edit", "會員暱稱: "+name);
                Log.i("edit", "密碼: "+password);
                Log.i("edit", "Email: "+email);
            }
        });
    }
}

4.3、按鈕Button

4.3.1、普通按鈕

在螢幕上新增按鈕後,還需要為按鈕新增單擊事件監聽器,才能讓按鈕發揮其特有的用途。Android提供了兩種為按鈕新增單擊事件監聽器的方法,一種是在Java程式碼中完成,例如,在Activity的onCreate0)方法中完成,具體的程式碼如下:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
            }
        });
    }

另一種是在Activity中編寫一個包含Viw型別引數的方法,並且將要觸發的動作程式碼放在該方法中,然後在佈局檔案中,通過android:onClick屬性指定對應的方法名實現。例如,在Activity中編寫一個名為myClickO的方法,關鍵程式碼如下:

public void myClick(View view){
            
        }

那麼就可以在佈局檔案中通過android:onClick="myClick"語句為按鈕新增單擊事件監聽器。

4.3.2、圖片按鈕

圖片按鈕與普通按鈕的使用方法基本相同,只不過圖片按鈕使用mageButton:標記定義,並且可以為其指定android:src屬性,用於設定要顯示的圖片。在佈局檔案中新增影象按鈕的基本語法格式如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="普通按鈕"
        android:id="@+id/button1"
        tools:ignore="MissingConstraints" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher_background"
        android:onClick="myClick"
        android:id="@+id/button2"
        tools:ignore="OnClick" />


</LinearLayout>
package com.example.imgbuttonproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button viewById = (Button) findViewById(R.id.button1);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast toast = Toast.makeText(MainActivity.this,"你點選了普通按鈕",Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }
    public void myClick(View view){
        Toast toast = Toast.makeText(MainActivity.this,"你點選了圖片按鈕",Toast.LENGTH_SHORT);
        toast.show();
    }
}

4.4、單選按鈕複選框

在Android中,單選按鈕和複選框都繼承了普通按鈕,因此,它們都可以直接使用普通按鈕支援的各種屬性和方法。與普通按鈕不同的是,它們提供了可選中的功能。下面分別對單選按鈕和複選框進行詳細介紹。

4.4.1、單選按鈕

在預設情況下,單選按鈕顯示為一個圓形圖示,並且在該圖示旁邊放置一些說明性文字。在程式中,一般將多單選按鈕放置在按鈕組中,使這些單選按鈕表現出某種功能,當用戶選中某個單選按鈕後,按鈕組中的其他按鈕將被自動取消選中狀態。在Android中,單選按鈕使用RadioButton表示,而RadioButton類又是Button的子類,所以單選按鈕可以直接使用Button支援的各種屬性。

RadioButton元件的android:checked屬性用於指定選中狀態,屬性值為true時,表示選中;屬性值為false時,表示取消選中,預設為false。

通常情況下,RadioButton元件需要與RadioGroup元件一起使用,組成一個單選按鈕組。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="性別"
        android:textSize="50px" />
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/radioGroup1">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男"
            android:id="@+id/radio1"
            android:checked="true"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女"
            android:id="@+id/radio2"/>
    </RadioGroup>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交"
        android:id="@+id/button1"/>
</LinearLayout>

在螢幕中新增單選按鈕組後,還需要獲取單選按鈕組中選中項的值,通常存在以下兩種情況:一種是在改變單選按鈕組的值時獲取;另一種是在單擊其他按鈕時獲取。下面分別介紹這兩種情況所對應的實現方法。在改變單選按鈕組的值時獲取選中項的值時,首先需要獲取單選按鈕組,然後為其新增OnCheckedChangeListener,並在其onCheckedChanged()方法中根據引數checkedId獲取被選中的單選鈕,並通過其getTextO方法獲取該單選按鈕對應的值。例如,要獲取id屬性為radioGroupl的單選按鈕組的值,可以通過下面的程式碼實現

RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton radioButton = (RadioButton) findViewById(i);
                Toast.makeText(MainActivity.this, "你的性別是:"+radioButton.getText(), Toast.LENGTH_SHORT);
            }
        });

單擊其他按鈕時獲取選中項的值時,首先需要在該按鈕的單擊事件監聽器的onClickO方法中,通過for迴圈語句遍歷當前單選按鈕組,並根據被遍歷到的單選按鈕的isCheckedO方法判斷該按鈕是否被選中,當被選中時,通過單選按鈕的getTextO)方法獲取對應的值。例如,要在單擊“提交"”按鈕時,獲取id屬性為radioGroupl的單選按鈕組的值,可以通過下面的程式碼實現。

RadioGroup radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < radioGroup1.getChildCount(); i++) {
                    RadioButton radioButton = (RadioButton) radioGroup1.getChildAt(i);
                    if (radioButton.isChecked()){
                        radioButton.getText();
                        break;
                    }
                }
            }
        });

4.4.2、複選框

在預設情況下,複選框顯示為一個方塊圖示,並且在該圖示旁邊放置一些說明性文字。與單選按鈕唯一不同的是複選框可以進行多選設定,每一個複選框都提供“選中”和“不選中”兩種狀態。在Android中,複選框使用CheckBox表示,而CheckBox類又是Button的子類,所以可以直接使用Button支援的各種屬性。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="愛好"
        android:width="100px"
        android:height="50px"
        android:gravity="right" />
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="音樂"
        android:id="@+id/like1"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="學習"
        android:id="@+id/like2"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="體育"
        android:id="@+id/like3"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交"
        android:id="@+id/button"/>
</LinearLayout>
package com.example.fuxuankuang;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;

public class MainActivity extends AppCompatActivity {

    private CompoundButton.OnCheckedChangeListener checkbox = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b){
                Log.i("複選框", "選中: "+compoundButton.getText().toString());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CheckBox checkBox1 = (CheckBox) findViewById(R.id.like1);
        CheckBox checkBox2 = (CheckBox) findViewById(R.id.like2);
        CheckBox checkBox3 = (CheckBox) findViewById(R.id.like3);
        checkBox1.setOnCheckedChangeListener(checkbox);
        checkBox2.setOnCheckedChangeLisetener(checkbox);
        checkBox3.setOnCheckedChangeListener(checkbox);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String like = "";
                if (checkBox1.isChecked()){
                    like = like + checkBox1.getText().toString();
                }
                if (checkBox2.isChecked()){
                    like = like + checkBox2.getText().toString();
                }
                if (checkBox3.isChecked()){
                    like = like + checkBox3.getText().toString();
                }
                Log.i("複選框", "愛好是: " + like);
            }
        });
    }
}

4.5、影象ImageView

ImageView是用於在介面上展示圖片的一個控制元件,它可以讓我們的程式介面變得更加豐富多彩。學習這個控制元件需要提前準備好一些圖片,圖片通常都是放在以“drawable”開頭的目錄下的。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/image"
        android:src="@drawable/icon03"
        android:layout_gravity="center"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="切換"
        android:layout_gravity="center_vertical|right"/>

</FrameLayout>
package com.example.imageproject;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    int i = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageView = (ImageView) findViewById(R.id.image);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                i++;
                if (i % 2 == 0){
                    imageView.setImageResource(R.drawable.icon04);
                }else {
                    imageView.setImageResource(R.drawable.icon03);
                }

            }
        });
    }
}

4.6、列表選擇框

Android中提供的列表選擇框(Spinner)相當於在網頁中常見的下拉列表框,通常用於提供一系列可選擇的列表項供使用者進行選擇,從而方便使用者。

其中,android:entries為可選屬性,用於指定列表項,如果在佈局檔案中不指定該屬性,可以在Java程式碼中通過為其指定介面卡的方式指定;android:prompt屬性也是可選屬性,用於指定列表選擇框的標題。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/ctype"
        android:id="@+id/spread1"/>

</LinearLayout>

編寫用於指定列表項的陣列資原始檔,並將其儲存在res\values目錄中,這裡將其命名為arrays.xml,在該檔案中新增一個字串陣列,名稱為ctype,具體程式碼如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ctype">
        <item>身份證</item>
        <item>學生證</item>
        <item>工作證</item>
        <item>軍人證</item>
        <item>其他證</item>
    </string-array>
</resources>
package com.example.spinnerproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spinner = (Spinner) findViewById(R.id.spread1);
        spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String s = adapterView.getItemAtPosition(i).toString();
                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT);
            }
        });
    }
}

4.7、列表檢視


通過介面卡指定列表項來進行建立

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView1"
        android:divider="@drawable/ic_launcher_background"
        android:dividerHeight="3px"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="arrs">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
    </string-array>
</resources>
package com.example.listviewproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.listView1);
        //建立介面卡
        ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(this,
                R.array.arrs, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String s = adapterView.getItemAtPosition(i).toString();
                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Activity繼承ListActivity實現

package com.example.listviewproject01;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String[] str = new String[]{"1", "2", "3", "4"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
                androidx.appcompat.R.layout.support_simple_spinner_dropdown_item, str);
        setListAdapter(arrayAdapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        String s = l.getItemAtPosition(position).toString();
        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
    }
}

4.8、日期時間拾取器

為了讓使用者能夠選擇日期和時間,Android提供了日期、時間拾取器,分別是DatePicker元件和TimePicker元件。這兩個元件使用比較簡單,可以在Android Studio的視覺化介面設計器中,選擇對應的元件並拖曳到佈局檔案中。為了可以在程式中獲取使用者選擇的日期、時間,還需要為DatePicker和TimePicker元件新增事件監聽器。其中,DatePicker元件對應的事件監聽器是OnDateChangedListener,而TimePicker元件對應的事件監聽器是OnTimeChangedListener.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <DatePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        tools:ignore="MissingConstraints" />
    <TimePicker
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/timePicker"
        tools:ignore="MissingConstraints" />

</LinearLayout>
package com.example.dataandtimeproject;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

@RequiresApi(api = Build.VERSION_CODES.N)
public class MainActivity extends AppCompatActivity {

    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);

    public void show(int year, int month, int day, int hour, int minute){
        String str = year + "年" + month + 1 + "月" + day + "日" + hour + "時" + minute + "分";
        Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker);
        TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
                MainActivity.this.year = year;
                MainActivity.this.month = month;
                MainActivity.this.day = day;
                show(year, month, day, hour, minute);
            }
        });
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int i, int i1) {
                MainActivity.this.hour = i;
                MainActivity.this.minute = i1;
                show(year, month, day, hour, minute);
            }
        });
    }
}

4.9、計時器

計時器(Chronometer)元件可顯示從某個起始時間開始,一共過去了多長時間的文字。由於該元件繼承自TextView,所以它以文字的形式顯示內容。使用該元件也比較簡單,通常只需要使用以下5個方法。

setBase():用於設定計時器的起始時間。
setFormat():用於設定顯示時間的格式。
start():用於指定開始計時。
stop():用於指定停止計時。
setOnChronometerTickListener():用於為計時器繫結事件監聽器,當計時器改變時觸發該監聽器。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Chronometer
        android:layout_width="match_parent"
        android:text="chronometer"
        android:layout_height="match_parent"
        android:gravity="center"
        android:id="@+id/chronometer"/>

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.chronomterproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.setFormat("已用時間:%s");
        chronometer.start();
    }
}

5、範例

1、實現跟蹤滑鼠單擊狀態的圖片按鈕。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:background="#0000"
        android:src="@drawable/button_state"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/mmexport1647693561983"/>
    <item android:state_pressed="false" android:drawable="@drawable/mmexport1647693579357"/>
</selector>
package com.example.fanli_anniuproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "1", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

2、實現帶圖示的ListView.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        tools:ignore="MissingConstraints" />


</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/image"
        android:paddingTop="20px"
        android:paddingRight="10px"
        android:paddingBottom="20px"
        android:adjustViewBounds="true"
        android:maxWidth="72px"
        android:maxHeight="72px"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:padding="10px"
        android:layout_gravity="center"/>
</LinearLayout>
package com.example.fanli_listviewproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = (ListView) findViewById(R.id.listView);
        int[] imageId = new int[]{R.drawable.icon01, R.drawable.icon02,
                R.drawable.icon03, R.drawable.icon04, R.drawable.icon05, R.drawable.icon06};
        String[] str = new String[]{"1", "2", "3", "4", "5", "6"};
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (int i = 0; i < imageId.length; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("image", imageId[i]);
            map.put("title", str[i]);
            arrayList.add(map);
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, arrayList,
                R.layout.items, new String[]{"title", "image"}, new int[]{R.id.text, R.id.image});
        listView.setAdapter(simpleAdapter);
    }
}

說明:SimpleAdapter類的構造方法SimpleAdapter(Context context,List?extends Map<String,?>>data,int resource.,String[]from,int to)中,引數context用於指定關聯SimpleAdapter執行的檢視上下文;引數data用於指定一個基於Map的列表,該列表中的每個條目對應列表中的一行;引數resource用於指定一個用於定義列表專案的檢視佈局檔案的唯一標識;引數from用於指定一個將被新增到Map上關聯每一個專案的列名稱的陣列;引數to用於指定一個與引數from顯示列對應的檢視id的陣列。