如何在 Android TextView 中使用 charAt()?


本例演示如何在 Android TextView 中使用 charAt()。

步驟 1 − 在 Android Studio 中建立一個新專案,依次轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 向 res/layout/activity_main.xml 新增以下程式碼。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>

在上述程式碼中,我們已將名稱指定為 EditText,當用戶單擊按鈕時,它將獲取資料並查詢第 5 個字元。

步驟 3 − 向 src/MainActivity.java 新增以下程式碼

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 5) {
                  char ch = name.getText().toString().charAt(5);
                  text.setText("5 th character is " + String.valueOf(ch));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}

我們來試著執行你的應用程式。我假設你已將你的實際 Android 移動裝置連線到你的計算機。要從 Android Studio 執行應用程式,請開啟一個專案的 activity 檔案,然後從工具欄中單擊執行  圖示。從選項中選擇你的移動裝置,然後檢查你的移動裝置上顯示的預設螢幕−

在上方的結果中,我們看到第 5 個字元為 M,這是因為索引從第 0 個位置開始。

點選此處下載專案程式碼

更新時間: 30-Jul-2019

354 瀏覽數

職業啟航

完成課程,獲得認證

開始學習
廣告