zoukankan      html  css  js  c++  java
  • Android学习之SharedPreferences

    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>

  • 相关阅读:
    100+ Python挑战性编程练习(1)
    python面试题--初级(二)
    python面试题--初级(一)
    centos查看iptables和firewall防火墙状态、开启、关闭防火墙
    Keepalived nginx HA负载均衡
    windows10安装SQLServer 2008 R2详细说明
    CentOS安装mysql5.7
    centOS7.5安装docker
    redis哨兵选举算法--raft
    CentOS7.5安装GitLab及汉化
  • 原文地址:https://www.cnblogs.com/zhouhb/p/4177702.html
Copyright © 2011-2022 走看看