如何在 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:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="100dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:gravity="center"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">
   </TextView>
</LinearLayout>

在上述代码中,我们已获取文本视图以显示段落,吐司将显示有关单词数的信息。

步骤 3 − 将以下代码添加到 src/MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   TextView text;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      text = findViewById(R.id.text);
      text.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                    Lorem Ipsum has been the industry's standard dummy text ever since the
                    1500s, when an unknown printer took a galley of type and scrambled it to
                    make a type specimen book. It has survived not only five centuries, but
                    also the leap into electronic typesetting, remaining essentially unchanged.
                    It was popularised in the 1960s with the release of Letraset sheets
                    containing Lorem Ipsum passages, and more recently with desktop publishing
                    software like Aldus PageMaker including versions of Lorem Ipsum.");
      String[] para = text.getText().toString().split("\s+");
      Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
   }
}

让我们尝试运行您的应用程序。我假设您已将实际 Android 移动设备连接到计算机。要从安卓工作室运行应用,请打开您的其中一个项目活动文件,单击工具栏上的运行  图标。选择您的移动设备作为选项,然后检查将显示默认屏幕的移动设备 –

单击 此处 下载项目代码

更新日期:2020 年 6 月 26 日

531 次浏览

开启您的职业生涯生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.