5.09作业

5.9作业!

我的理解!主要是两个按钮的点击事件上要做什么!所以重点是按钮上的代码,那布局代码也就不做详细的说明了,而且以前就有过类似的布局代码做过,以下是主要的布局代码!
<LinearLayout 
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.zhdn.a1.MainActivity">
<TextView
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    android:text="登录界面"
    android:textSize="22sp" />

<EditText
    android:id="@+id/ev_userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入用户名" />
<EditText
    android:id="@+id/ev_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入密码" />
<Button
    android:id="@+id/btn_login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="写入"
    android:textSize="20sp"
    android:onClick="onClick"
    android:layout_gravity="center"/>
<Button
    android:id="@+id/btn_b"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="读取"
    android:textSize="20sp"
    android:onClick="onClick"
    android:layout_gravity="center"/>

</LinearLayout>
主要的java代码!
public class MainActivity extends AppCompatActivity {
private EditText ev_userName;
private EditText ev_password;
private Button btn_login;
private Button btn_b;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    ev_userName = (EditText) findViewById(R.id.ev_userName);
    ev_password = (EditText) findViewById(R.id.ev_password);
    btn_login = (Button) findViewById(R.id.btn_login);
    btn_b=(Button)findViewById(R.id.btn_b);
    }
public void onClick(View view){
switch (view.getId()){
case R.id.btn_login:
    String username = ev_userName.getText().toString();
    String password = ev_password.getText().toString();
    write(username,password);
    break;
case R.id.btn_b:
    read();
    break;

}
}
private void read() {
    SharedPreferences prefs = getSharedPreferences("data.text", MODE_PRIVATE); //获取对象,读取data文件
    String username = prefs.getString("username", ""); //获取文件中的数据
    String password = prefs.getString("password", "");
    Toast.makeText(MainActivity.this, "用户名:"+username+"密码:"+password, Toast.LENGTH_LONG).show();
}

private void write(String username, String password) {
    SharedPreferences.Editor editor = getSharedPreferences("data.text", MODE_PRIVATE).edit();//获取对象,并且命名文件的名称
    editor.putString("username",username );  //保存数据
    editor.putString("password",password);
    editor.commit();
    editor.clear();
    Toast.makeText(MainActivity.this, "保存成功!", Toast.LENGTH_LONG).show();
}
}
以下是程序实现效果图!

posted @ 2017-05-09 20:28  yeech  阅读(124)  评论(0编辑  收藏  举报