Andriod學習之SharedPreferences,andriod

來源:互聯網
上載者:User

Andriod學習之SharedPreferences,andriod

SharedPreferences使用索引值對的方式來儲存資料,並支援多種不同類型的資料存放區。

1、介面布局

<TableLayout 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"
tools:context=".MainActivity"
android:stretchColumns="0"> <!-- 展開第1列 -->

<TableRow>

<EditText
android:id="@+id/txtWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:hint="請輸入" />

<Button
android:id="@+id/btnWrite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="寫入" />
</TableRow>


<TableRow>

<TextView
android:id="@+id/txtRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />

<Button
android:id="@+id/btnRead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="讀取" />
</TableRow>

</TableLayout>

2、代碼

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btnWrite = (Button) findViewById(id.btnWrite);
btnWrite.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText txtEditText = (EditText) findViewById(R.id.txtWrite);
String string = txtEditText.getText().toString();

//MODE_PRIVATE和傳入0相同,表示只有當前應用程式才能對這個SharedPreferences檔案進行操作
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name", string);
editor.commit();
}
});
Button btnRead = (Button) findViewById(id.btnRead);
btnRead.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
String string = sharedPreferences.getString("name", "");
TextView textView = (TextView) findViewById(R.id.txtRead);
textView.setText(string);
}
});

}

}

可以通過DDMS匯出產生的檔案。

檔案內容如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">張三</string>
</map>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.