通常 android的edittext
每重開一次就要重新輸入資料
對使用者會很不方便
例如:每次登入都要重新輸入帳號.....
所以我們就來做一個記憶的功能
讓大家不用在這麼麻煩!
以下開始!!
-----
以下是android的xml檔:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.leave.MainActivity" >
<EditText
android:id="@+id/acc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="16dp"
android:layout_marginTop="46dp"
android:hint="帳號 "
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/acc"
android:layout_below="@+id/acc"
android:layout_marginTop="43dp"
android:text="登入" />
</RelativeLayout>
----
以下是MainActivity.java
public class MainActivity extends Activity {
private Button login;
private EditText acc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.login);
acc=(EditText)findViewById(R.id.acc);
SharedPreferences myrecord=getPreferences(Activity.MODE_PRIVATE);
String name_str=myrecord.getString("acc", "");
acc.setText(name_str);
login.setOnClickListener(getDBRecord);
}
private Button.OnClickListener getDBRecord = new Button.OnClickListener() {
public void onClick(View v) {
String car_num=acc.getText().toString().toUpperCase();
SharedPreferences myrecord=getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor edit=myrecord.edit();
edit.putString("acc", acc.getText().toString());
edit.commit();
}
};
}
----
以上,即使你關掉APP
你的資料依然會被記憶喔~~
留言列表