标签:android blog http java os io width 2014
简单演示一下SharedPreference在程序中的应用:
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=".MainActivity" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="跳转"/> <TextView android:id="@+id/text" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerInParent="true" android:text=""/> </RelativeLayout>
两个activity的跳转只是演示一个text的值的获取就随便设置了一下textview的可见或者不可见
第一个activity:
public class MainActivity extends Activity implements OnClickListener {
SharedPreferences share;
Editor edit;
String str;
static String strValue = "测试";
Button button;
TextView text;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
text = (TextView)findViewById(R.id.text);
text.setVisibility(View.INVISIBLE);
share = this.getSharedPreferences("name",Context.MODE_WORLD_WRITEABLE);
str = share.getString("name", strValue);
edit = share.edit();
setString();
}
private void setString(){
edit.putString("name", strValue);
edit.commit();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(getApplicationContext(), ValueActivity.class);
startActivity(intent);
finish();
System.exit(0);
}
}
另一个activity当中获得共享的key -- value值
public class ValueActivity extends Activity {
SharedPreferences share;
String str;
TextView text;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.text);
text.setVisibility(View.VISIBLE);
Editor edit = this.getSharedPreferences("name", Context.MODE_WORLD_WRITEABLE).edit();
str = this.getSharedPreferences("name", Context.MODE_WORLD_WRITEABLE).getString("name", MainActivity.strValue);
text.setText(str);
}
}
最后是酱紫的:
SharedPreferences DEMO,布布扣,bubuko.com
标签:android blog http java os io width 2014
原文地址:http://www.cnblogs.com/tiejiangweigaibianercunzai/p/3869106.html