Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

จะพิมพ์จำนวนคำใน textview ใน Android ได้อย่างไร?


ตัวอย่างนี้สาธิตวิธีการพิมพ์จำนวนคำในมุมมองข้อความใน Android

ขั้นตอนที่ 1 - สร้างโครงการใหม่ใน Android Studio ไปที่ไฟล์ ⇒ โครงการใหม่และกรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโครงการใหม่

ขั้นตอนที่ 2 - เพิ่มรหัสต่อไปนี้ใน res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://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("\\s+");
      Toast.makeText(MainActivity.this, "" + para.length, Toast.LENGTH_LONG).show();
   }
}

มาลองเรียกใช้แอปพลิเคชันของคุณกัน ฉันคิดว่าคุณได้เชื่อมต่ออุปกรณ์มือถือ Android จริงกับคอมพิวเตอร์ของคุณ ในการรันแอพจาก android studio ให้เปิดไฟล์กิจกรรมของโปรเจ็กต์แล้วคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก จากนั้นตรวจสอบอุปกรณ์มือถือของคุณซึ่งจะแสดงหน้าจอเริ่มต้นของคุณ –

จะพิมพ์จำนวนคำใน textview ใน Android ได้อย่างไร?