如何在 Android 文字檢視中使用 split()?
本例演示如何在 Android 文字檢視中使用 split()
步驟 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>
在上例中,我們使用了編輯文字作為 name 時,當用戶點選按鈕後,它將獲取資料並使用空格正則表示式對資料進行分隔。
步驟 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() >= 0) {
String[] replace = name.getText().toString().split("\s");
text.setText(String.valueOf(replace[1]));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}我們嘗試執行你的應用程式。我假設你已將你的真實安卓移動裝置連線到電腦。要從 android studio 執行該應用程式,開啟你的一個專案活動檔案並單擊工具欄中的
圖示。選擇你的移動裝置作為選項,然後檢查移動裝置上顯示的預設螢幕 −

以上結果中,輸入字串為“Krishna sai sai”。它按空格進行分隔並返回第 1 個索引值。
點選 此處 下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP