Ilham Satria Aji Pratama

1202164345/SI4002

9.1

Download project HelloSharedPrefs-Starter kemudian ubah pada bagian MainActivity menjadi seperti dibawah ini



import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
// Current count
private int mCount = 0;
// Current background color
private int mColor;
// Text view to display both count and color
private TextView mShowCountTextView;

// Key for current count
private final String COUNT_KEY = "count";
// Key for current color
private final String COLOR_KEY = "color";

// Shared preferences object
private SharedPreferences mPreferences;

// Name of shared preferences file
private String sharedPrefFile =
"com.example.android.hellosharedprefs";


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

// Initialize views, color, preferences
mShowCountTextView = findViewById(R.id.count_textview);
mColor = ContextCompat.getColor(this,
R.color.default_background);

mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);

// Restore preferences
mCount = mPreferences.getInt(COUNT_KEY, 0);
mShowCountTextView.setText(String.format("%s", mCount));
mColor = mPreferences.getInt(COLOR_KEY, mColor);
mShowCountTextView.setBackgroundColor(mColor);
}


public void changeBackground(View view) {
int color = ((ColorDrawable) view.getBackground()).getColor();
mShowCountTextView.setBackgroundColor(color);
mColor = color;
}


public void countUp(View view) {
mCount++;
mShowCountTextView.setText(String.format("%s", mCount));
}


public void reset(View view) {
// Reset count
mCount = 0;
mShowCountTextView.setText(String.format("%s", mCount));

// Reset color
mColor = ContextCompat.getColor(this,
R.color.default_background);
mShowCountTextView.setBackgroundColor(mColor);

// Clear preferences
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
}

/**
* Callback for activity pause. Shared preferences are saved here.
*/
@Override
protected void onPause() {
super.onPause();

SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt(COUNT_KEY, mCount);
preferencesEditor.putInt(COLOR_KEY, mColor);
preferencesEditor.apply();
}
}

9.2

Task 1

Buat project baru dan masukkan ke dalam layout activity main

<?xml version="1.0" encoding="utf-8"?>


<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.appwithsettings.MainActivity"
>

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay"
>

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
/>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email"
/>

</android.support.design.widget.CoordinatorLayout>

dan masukkan ke layout content_main

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.android.appwithsettings.MainActivity"
tools:showIn="@layout/activity_main"
>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

</android.support.constraint.ConstraintLayout>

Lalu pada java MainActivity tulis seperti berikut

package com.example.android.appwithsettings;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});

// Sets default values only once, first time this is called.
// The third argument is a boolean that indicates whether
// the default values should be set more than once. When false,
// the system sets the default values only if this method has never
// been called in the past.
android.support.v7.preference.PreferenceManager
.setDefaultValues(this,
R.xml.preferences, false);

// Read the settings from the shared preferences, put them into the
// SettingsActivity, and display a toast.
SharedPreferences sharedPref =
android.support.v7.preference.PreferenceManager
.getDefaultSharedPreferences(this);
Boolean switchPref = sharedPref.getBoolean
(SettingsActivity.KEY_PREF_EXAMPLE_SWITCH, false);
Toast.makeText(this, switchPref.toString(),
Toast.LENGTH_SHORT).show();
}

/**
* Inflates the options menu and adds items to the menu.
*
*
@param menu Options menu
*
@return True if menu is inflated.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
// if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

/**
* Handles option menu selections and automatically handles clicks
* on the Up button in the app bar.
*
*
@param item Item in options menu
*
@return True if Settings is selected in the options menu.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

// If option menu item is Settings, return true.
if (id == R.id.action_settings) {
Intent intent = new Intent(this,
SettingsActivity.class);
startActivity(intent);
return true;
}

return super.onOptionsItemSelected(item);
}
}

Kemudian Buat dan masukkan SettingActivity seperti dibawah ini

package com.example.android.appwithsettings;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class SettingsActivity extends AppCompatActivity {
public static final String
KEY_PREF_EXAMPLE_SWITCH = "example_switch";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content,
new SettingsFragment()).commit();
}
}

Buat dan masukkan SettingFragment seperti dibawah

package com.example.android.appwithsettings;

import android.os.Bundle;
import android.support.v7.preference.PreferenceFragmentCompat;


public class SettingsFragment extends PreferenceFragmentCompat {

/**
* Called during onCreate(Bundle) to supply the preferences for this
* fragment. This calls setPreferenceFromResource to get the preferences
* from the XML file.
*
*
@param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*
@param rootKey If non-null, this preference fragment
* should be rooted with this key.
*/
@Override
public void onCreatePreferences(Bundle savedInstanceState,
String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}

}

Task 2

Masukkan di activity_main

<?xml version="1.0" encoding="utf-8"?>


<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.droidcafeinput.MainActivity"
>

<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay"
>

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
/>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
app:srcCompat="@drawable/ic_shopping_cart"
/>

</android.support.design.widget.CoordinatorLayout>

Masukkan di activity_order

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.droidcafeinput.OrderActivity"
>

<TextView
android:id="@+id/order_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:text="@string/order_label_text"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<TextView
android:id="@+id/name_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="@string/name_label_text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/order_textview"
/>

<EditText
android:id="@+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="@string/enter_name_hint"
android:inputType="textPersonName"
app:layout_constraintBaseline_toBaselineOf="@+id/name_label"
app:layout_constraintStart_toEndOf="@+id/name_label"
/>

<TextView
android:id="@+id/address_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/address_label_text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/name_label"
/>

<EditText
android:id="@+id/address_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="@string/enter_address_hint"
android:inputType="textMultiLine"
app:layout_constraintBaseline_toBaselineOf="@+id/address_label"
app:layout_constraintStart_toEndOf="@+id/address_label"
/>

<TextView
android:id="@+id/phone_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/phone_label_string"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/address_text"
/>

<EditText
android:id="@+id/phone_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="@string/enter_phone_hint"
android:inputType="phone"
app:layout_constraintBaseline_toBaselineOf="@+id/phone_label"
app:layout_constraintStart_toEndOf="@+id/phone_label"
/>

<TextView
android:id="@+id/note_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/note_label_text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/phone_label"
/>

<EditText
android:id="@+id/note_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:ems="10"
android:hint="@string/enter_note_hint"
android:inputType="textCapSentences|textMultiLine"
app:layout_constraintBaseline_toBaselineOf="@+id/note_label"
app:layout_constraintStart_toEndOf="@+id/note_label"
/>

<TextView
android:id="@+id/delivery_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/choose_delivery_method"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/note_text"
/>

<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/delivery_label"
>

<RadioButton
android:id="@+id/sameday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="@string/same_day_messenger_service"
/>

<RadioButton
android:id="@+id/nextday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="@string/next_day_ground_delivery"
android:checked="true"
/>

<RadioButton
android:id="@+id/pickup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:text="@string/pick_up"
/>
</RadioGroup>

</android.support.constraint.ConstraintLayout>

Masukkan pada content_main

<?xml version="1.0" encoding="utf-8"?>


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.android.droidcafeinput.MainActivity"
tools:showIn="@layout/activity_main"
>

<TextView
android:id="@+id/textintro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/intro_text"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<ImageView
android:id="@+id/donut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:contentDescription="@string/donuts"
android:onClick="showDonutOrder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textintro"
app:srcCompat="@drawable/donut_circle"
/>

<ImageView
android:id="@+id/ice_cream"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:contentDescription="@string/ice_cream_sandwiches"
android:onClick="showIceCreamOrder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/donut"
app:srcCompat="@drawable/icecream_circle"
/>

<ImageView
android:id="@+id/froyo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:contentDescription="@string/froyo"
android:onClick="showFroyoOrder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ice_cream"
app:srcCompat="@drawable/froyo_circle"
/>

<TextView
android:id="@+id/donut_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/donuts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/donut"
app:layout_constraintTop_toTopOf="@+id/donut"
/>

<TextView
android:id="@+id/ice_cream_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/ice_cream_sandwiches"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/ice_cream"
app:layout_constraintTop_toTopOf="@+id/ice_cream"
/>

<TextView
android:id="@+id/froyo_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="24dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:text="@string/froyo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/froyo"
app:layout_constraintTop_toTopOf="@+id/froyo"
/>

</android.support.constraint.ConstraintLayout>

Pada MainActivity masukkan

package com.example.android.droidcafeinput;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

// Tag for the intent extra.
public static final String EXTRA_MESSAGE =
"com.example.android.droidcafeinput.extra.MESSAGE";

// The order message, displayed in the Toast and sent to the new Activity.
private String mOrderMessage;

/**
* Creates the content view, the toolbar, and the floating action button.
*
* This method is provided in the Basic Activity template.
*
*
@param savedInstanceState Saved instance state bundle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
OrderActivity.class);
intent.putExtra(EXTRA_MESSAGE, mOrderMessage);
startActivity(intent);
}
});

// Sets default values only once, first time this is called. The third
// argument is a boolean that indicates whether the default values
// should be set more than once. When false, the system sets the default
// values only the first time it is called.
PreferenceManager.setDefaultValues(this,
R.xml.pref_general, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notification, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_account, false);

// Read settings from the shared preferences and display a toast.
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
String marketPref = sharedPref
.getString("sync_frequency", "-1");
displayToast(marketPref);
}

/**
* Inflates the menu, and adds items to the action bar if it is present.
*
*
@param menu Menu to inflate.
*
@return Returns true if the menu inflated.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

/**
* Handles app bar item clicks.
*
*
@param item Item clicked.
*
@return True if one of the defined items was clicked.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_order:
Intent intent = new Intent(MainActivity.this,
OrderActivity.class);
intent.putExtra(EXTRA_MESSAGE, mOrderMessage);
startActivity(intent);
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
case R.id.action_status:
displayToast(getString(R.string.action_status_message));
return true;
case R.id.action_favorites:
displayToast(getString(R.string.action_favorites_message));
return true;
case R.id.action_contact:
displayToast(getString(R.string.action_contact_message));
return true;
default:
// Do nothing
}

return super.onOptionsItemSelected(item);
}

/**
* Displays a Toast with the message.
*
*
@param message Message to display
*/
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}

/**
* Shows a message that the donut image was clicked.
*/
public void showDonutOrder(View view) {
mOrderMessage = getString(R.string.donut_order_message);
displayToast(mOrderMessage);
}

/**
* Shows a message that the ice cream sandwich image was clicked.
*/
public void showIceCreamOrder(View view) {
mOrderMessage = getString(R.string.ice_cream_order_message);
displayToast(mOrderMessage);
}

/**
* Shows a message that the froyo image was clicked.
*/
public void showFroyoOrder(View view) {
mOrderMessage = getString(R.string.froyo_order_message);
displayToast(mOrderMessage);
}

}

Masukkan pada OrderActivity

package com.example.android.droidcafeinput;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

/**
* This activity handles radio buttons for choosing
* a delivery method for an order, and EditText input controls.
*/
public class OrderActivity extends AppCompatActivity {

/**
* Sets the content view to activity_order, and gets the intent and its
* data.
*
*
@param savedInstanceState Saved instance state bundle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);

// Get the intent and its data.
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.order_textview);
textView.setText(message);
}

/**
* Checks which radio button was clicked and displays a toast message to
* show the choice.
*
*
@param view The radio button view.
*/
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked.
switch (view.getId()) {
case R.id.sameday:
if (checked)
// Same day service
displayToast(
getString(R.string.same_day_messenger_service));
break;
case R.id.nextday:
if (checked)
// Next day delivery
displayToast(getString(R.string.next_day_ground_delivery));
break;
case R.id.pickup:
if (checked)
// Pick up
displayToast(getString(R.string.pick_up));
break;
default:
// Do nothing.
break;
}
}

/**
* Displays the actual message in a toast message.
*
*
@param message Message to display.
*/
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
}

Masukkan pada SettingActivity

package com.example.android.droidcafeinput;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.MenuItem;

import java.util.List;



public class SettingsActivity extends AppCompatPreferenceActivity {

/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener
sBindPreferenceSummaryToValueListener =
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();

if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);

// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);

} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);

} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));

if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}

} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};

/**
* Determines if the device has an extra-large screen. For example, 10"
* tablets are extra-large.
*/
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}

/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
*
@see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(
sBindPreferenceSummaryToValueListener);

// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener
.onPreferenceChange(preference, PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}

/**
* Sets up the action bar for the activity.
*
*
@param savedInstanceState Saved instance state bundle.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}

/**
* Set up the android.app.ActionBar, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}

@Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}

/**
* This method stops fragment injection in malicious applications.
* Make sure to deny any unknown fragments here.
*/
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| GeneralPreferenceFragment
.class.getName().equals(fragmentName)
|| DataSyncPreferenceFragment
.class.getName().equals(fragmentName)
|| NotificationPreferenceFragment
.class.getName().equals(fragmentName);
}

/**
* This fragment shows general preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment
extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);

// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue
(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}

/**
* This fragment shows notification preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment
extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
setHasOptionsMenu(true);

// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue
(
findPreference("notifications_new_message_ringtone"));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}

/**
* This fragment shows data and sync preferences only. It is used when the
* activity is showing a two-pane settings UI.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment
extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_account);
setHasOptionsMenu(true);

// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue
(findPreference("sync_frequency"));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}

Masukkan pada AppCompatPreferenceActivity

package com.example.android.droidcafeinput;

import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;


public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

private AppCompatDelegate mDelegate;

@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}

public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}

public void setSupportActionBar(@Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}

@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}

@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}

@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}

@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}

@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}

@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}

@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}

@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}

@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}

public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}

private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
}

--

--