如何在 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 執行應用,可以開啟專案的其中一個活動檔案,然後單擊工具欄的執行圖示 。選擇您的移動裝置作為選項,然後檢視您的移動裝置,它將顯示您的預設螢幕 –
單擊此處下載專案程式碼
廣告