如何在安卓文本框中使用 indexOf()?
此示例演示如何在 Android 文本框中使用 indexOf()。
步骤 1 − 在 Android Studio 中创建一个新项目,转到 File ⇒ New Project 并填写所有必需的详细信息以创建一个新项目。
步骤 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>
在以上代码中,我们将名称作为编辑文本,当用户单击按钮时,它将获取数据并返回 “sai” 的索引。
步骤 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) {
int index = name.getText().toString().indexOf("sai");
text.setText(String.valueOf(index));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
让我们尝试运行你的应用程序。我假设你已经将你的实际 Android 移动设备连接到了电脑。要从 Android Studio 运行应用程序,请打开其中一个项目的活动文件,然后从工具栏中单击运行
图标。选择你的移动设备作为选项,然后查看将显示你的默认屏幕的移动设备 −

在以上结果中,输入字符串 “Krishna sai”,它返回 sai 的索引为 8。
单击 此处 下载项目代码
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP