Monday, August 2, 2010

EditTextPreference

Further work on last exercise "Preferences and SharedPreferences", a EditTextPreference will be added here.

EditTextPreference

Modify mypreference.xml too add a EditTextPreference
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="checkboxvalue"
android:title="Checkbox"
android:defaultValue="true"
android:summary="CheckBoxPreference" />
<EditTextPreference
android:key="edittexvalue"
android:title="EditText"
android:summary="EditTextPreference" />
</PreferenceScreen>


Modify main.xml to have TextView for the EditTextPreference
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/setpreference"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set Preference"
/>
<TextView
android:id="@+id/checkboxstatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/edittextstatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


Modify AndroidPreference.java
package com.exercise.AndroidPreference;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidPreference extends Activity {

TextView checkBoxStatus, editTextStatus;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonSetPreference = (Button)findViewById(R.id.setpreference);
checkBoxStatus = (TextView)findViewById(R.id.checkboxstatus);
editTextStatus = (TextView)findViewById(R.id.edittextstatus);

buttonSetPreference.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(AndroidPreference.this, SetPreference.class));
}});
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_LONG).show();

SharedPreferences myPreference=PreferenceManager.getDefaultSharedPreferences(this);
checkBoxStatus.setText("CheckBox Status: " + myPreference.getBoolean("checkboxvalue", true));
editTextStatus.setText("EditText Status: " + myPreference.getString("edittexvalue", ""));
}
}



Download the files.