如何在 Android 中驗證文字檢視資料僅為數字?


本示例演示如何在 Android 中驗證文字檢視資料僅為數字。

步驟 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:gravity="center"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:textSize="30sp"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</LinearLayout>

在以上程式碼中,我們使用一個文字檢視來顯示數字。

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

package com.example.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   TextView textView;
   Location location;
   double describeContents;
   List<Address> addresses;
   Geocoder geocoder;
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText("123456789");
      Boolean isdigit =TextUtils.isDigitsOnly(textView.getText());
      Toast.makeText(MainActivity.this,""+isdigit,Toast.LENGTH_LONG).show();
   }
}

我們嘗試執行你的應用程式。我假設你已將實際的 Android 移動裝置與計算機連線起來。要從 Android Studio 中執行應用程式,開啟專案的其中一個活動檔案,然後單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢視你的移動裝置,其中會顯示你的預設螢幕 −

點選 此處 下載專案程式碼

更新於: 2020 年 6 月 26 日

142 次瀏覽

開啟你的 事業

完成課程即可獲得認證

開始學習
Advertisement
© . All rights reserved.