android--資料儲存
阿新 • • 發佈:2020-12-20
java程式碼
1 package com.example.myapplication; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.content.SharedPreferences; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.EditText; 10 import android.widget.TextView;11 import android.widget.Toast; 12 13 publicclassSharedActivity extends AppCompatActivity { 14 privateEditText shared1; 15 privateButton shared2,shared3; 16 privateTextView shared4; 17 privateSharedPreferences mSharedPreferences; 18 privateSharedPreferences.Editor mEditor; 19 @Override 20 protectedvoidonCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_shared); 23 shared1=findViewById(R.id.shared1); 24 shared2=findViewById(R.id.shared2); 25 shared3=findViewById(R.id.shared3); 26 shared4=findViewById(R.id.shared4); 27 28 mSharedPreferences=getSharedPreferences("data",MODE_PRIVATE);29 mEditor=mSharedPreferences.edit(); 30 31 shared2.setOnClickListener(newView.OnClickListener() { 32 @Override 33 publicvoidonClick(View view) { 34 mEditor.putString("name",shared1.getText().toString()); 35 mEditor.commit(); 36 Toast.makeText(SharedActivity.this,"儲存完畢",Toast.LENGTH_SHORT).show(); 37 } 38 }); 39 shared3.setOnClickListener(newView.OnClickListener() { 40 @Override 41 publicvoidonClick(View view) { 42 shared4.setText(mSharedPreferences.getString("name","")); 43 } 44 }); 45 }
xml
1 <?xml version="1.0"encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 android:padding="10dp" 7 > 8 <EditText 9 android:layout_marginTop="50dp" 10 android:id="@+id/shared1" 11 android:layout_width="match_parent" 12 android:layout_height="wrap_content" 13 android:hint="請輸入要儲存的名字:" 14 android:textSize="20sp"/> 15 <Button 16 android:layout_marginTop="20dp" 17 android:id="@+id/shared2" 18 android:layout_width="match_parent" 19 android:layout_height="wrap_content" 20 android:textSize="20dp" 21 android:text="儲存"/> 22 <Button 23 android:id="@+id/shared3" 24 android:layout_marginTop="20dp" 25 android:layout_width="match_parent" 26 android:layout_height="wrap_content" 27 android:textSize="20dp" 28 android:text="檢視"/> 29 <TextView 30 android:layout_marginTop="40dp" 31 android:id="@+id/shared4" 32 android:layout_width="match_parent" 33 android:layout_height="wrap_content" 34 android:textSize="20dp"/> 35 36 </LinearLayout>