android studio版本:2023.3.1 patch2
例程:readtextviewIDsaveandread
本例程是个过渡例程,如果单是实现下图的目的有更简单的方法,但这个方法是下一步工作的基础,所以一定要做。
例程功能:将两个textview的text保存到文件,再通过一个按钮读出文件内容,并将两个值分别赋值给另两个textview的text.实现修改多个textview的text的目的。
例程演示:
代码:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><TextViewandroid:id="@+id/textView2"android:layout_width="150dp"android:layout_height="35dp"android:background="#00BCD4"android:text="Hello World!"android:textSize="24dp"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView1"app:layout_constraintVertical_bias="0.099" /><TextViewandroid:id="@+id/textView1"android:layout_width="110dp"android:layout_height="35dp"android:layout_marginTop="288dp"android:background="#00BCD4"android:text="演示内容"android:textSize="24dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.498"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="104dp"android:layout_marginTop="48dp"android:text="存储"android:textSize="20dp"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView3" /><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="48dp"android:layout_marginTop="4dp"android:text="读取"android:textSize="20dp"app:layout_constraintStart_toEndOf="@+id/button1"app:layout_constraintTop_toTopOf="@+id/button1" /><TextViewandroid:id="@+id/textView3"android:layout_width="150dp"android:layout_height="35dp"android:layout_marginStart="68dp"android:layout_marginTop="48dp"android:text="TextView"android:textSize="24dp"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textView2" /><TextViewandroid:id="@+id/textView4"android:layout_width="140dp"android:layout_height="35dp"android:layout_marginStart="32dp"android:text="TextView"android:textSize="24dp"app:layout_constraintStart_toEndOf="@+id/textView3"app:layout_constraintTop_toTopOf="@+id/textView3" /></androidx.constraintlayout.widget.ConstraintLayout>
由于“写文件”还是用到了前一篇(android studio 读写文件操作(方法一)(转)-CSDN博客)的方法,所以保留了相关内容,其实不用也行,懒得改。
FileHelper.java
package com.shudu.readtextviewidsaveandread;import android.content.Context;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileHelper {private Context mContext;public FileHelper() {}public FileHelper(Context mContext) {super();this.mContext = mContext;}/** 这里定义的是一个文件保存的方法,写入到文件中,所以是输出流* */public void save(String filename, String filecontent) throws Exception {//这里我们使用私有模式,创建出来的文件只能被本应用访问,还会覆盖原文件哦FileOutputStream output = mContext.openFileOutput(filename, Context.MODE_PRIVATE);output.write(filecontent.getBytes()); //将String字符串以字节流的形式写入到输出流中output.close(); //关闭输出流}/** 这里定义的是文件读取的方法* */public String read(String filename) throws IOException {//打开文件输入流FileInputStream input = mContext.openFileInput(filename);byte[] temp = new byte[1024];StringBuilder sb = new StringBuilder("");int len = 0;//读取文件内容:while ((len = input.read(temp)) > 0) {sb.append(new String(temp, 0, len));}//关闭输入流input.close();return sb.toString();}}
mainactivity.java
package com.shudu.readtextviewidsaveandread;import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;public class MainActivity extends AppCompatActivity implements View.OnClickListener {private TextView textview1,textview2,textview3,textview4;private Button button1,button2;private Context mContext;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_main);mContext = getApplicationContext();//string的上下文对象,我也不知道是啥,没它不行。ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);return insets;});textview1=(TextView)findViewById(R.id.textView1);textview2 = (TextView) findViewById(R.id.textView2);textview3 = (TextView) findViewById(R.id.textView3);textview4 = (TextView) findViewById(R.id.textView4);button1 = (Button) findViewById(R.id.button1);button2 = (Button) findViewById(R.id.button2);button1.setOnClickListener(this);button2.setOnClickListener(this);}public void onClick(View view) {switch (view.getId()){case R.id.button1://写FileHelper fHelper = new FileHelper(mContext);String filename = "10000.txt";String filedetail = textview1.getText().toString();String filedetail1= textview2.getText().toString();String newstring=filedetail+","+filedetail1;try {fHelper.save(filename, newstring);System.out.println("文件名为:"+filename);Toast.makeText(getApplicationContext(), "数据写入成功", Toast.LENGTH_SHORT).show();} catch (Exception e) {e.printStackTrace();Toast.makeText(getApplicationContext(), "数据写入失败", Toast.LENGTH_SHORT).show();}break;case R.id.button2://读//FileHelper fHelper2 = new FileHelper(getApplicationContext());readFileAndSplit();break;}}@Overridepublic void onPointerCaptureChanged(boolean hasCapture) {}private void readFileAndSplit(){File file =new File(getFilesDir(),"10000.txt");//这个必须单独写,不能直接写到try里面,不知道为啥。try(BufferedReader reader=new BufferedReader(new FileReader(file))){String line=reader.readLine();//读取行String[] parts=line.split(",");//split按照“,”分割,并写进part1数组String str1=parts[0].trim();//读数组第一个值,trim是去年后面空格。String str2=parts[1].trim();//读数组第二个值textview3.setText(str1);textview4.setText(str2);} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}
}
中间保存文件位置参照前一篇(方法一)。
有关this,switch的R.id错误,参照android studio 按钮点击事件的实现方法(三种方法)_安卓按钮点击事件-CSDN博客
相关内容修改。