如何在 Android textview 中使用 substring()?
本示例演示如何在 Android textview 中使用 substring() 方法。
第 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>
在上面的程式碼中,我們已將名稱作為編輯文字,當用戶單擊按鈕時,它將獲取資料並返回子串值。
第 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 substring = name.getText().toString().substring(0,5);
text.setText(String.valueOf(substring));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}我們來試著執行你的應用程式。我假設你已將你的真機 Android 移動裝置與你的計算機連線。要在 Android Studio 中執行應用,請開啟你的一個專案活動檔案並單擊工具欄中的執行
圖示。選擇你的移動裝置作為選項,然後檢查將顯示預設螢幕的你的移動裝置 -

在上面的結果中,將字串輸入為“sairamkrishnaprasadkrishnamm”,它返回從第 0 個索引到第 5 個索引的子字串值,即 saira
點選 此處 下載專案程式碼
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP