App名和工程名都为example1_1,活动名为MainActivity,建立一个Android App项目,项目配置项保持默认,然后在布局文件activity_main.xml中设计界面,在活动程序文件MainActivity.java中编写total方法的代码,最后编写这个App。
<?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:id="@+id/LinearLayout1"
android:orientation="vertical"
tools:context=".MainActivity"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1"
android:ems="10"
android:hint="请输入一个字符串"
android:text="">
<requestFocus/>
</EditText>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:onClick="total"
android:text="统计" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/textView1"
android:text=""/>
</LinearLayout>
MainActivity.java活动源程序文件的内容如下:
package com.example.test01;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void total(View view){
EditText editText1=(EditText)this.findViewById(R.id.editText1);
String str=editText1.getText().toString();
int strlen=str.length();
TextView textView1=(TextView)this.findViewById(R.id.textView1);
textView1.setText(""+strlen);
}
}