如何在 Android 中打印 textview 中的段落数?
本例演示了如何在 Android 中打印 textview 中的段落数。
步骤 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>
在上述代码中,我们已采用 textview 来显示段落,而 toast 将显示段落数的相关信息。
步骤 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("\r
\r
"); Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show(); } }
让我们尝试运行您的应用程序。我假设已将实际的 Android 移动设备连接到计算机。要从 Android Studio 运行应用,可以打开项目的其中一个活动文件,然后单击工具栏的运行图标 。选择您的移动设备作为选项,然后查看您的移动设备,它将显示您的默认屏幕 –
单击此处下载项目代码
广告