Vous êtes sur la page 1sur 13

Ex. No.

: 7 Date: 27/02/2018

Menus and Shared Preferences

AIM:

To develop an app that uses the different android menus such as the context menu
(floating and action mode), the options menu and pop-up menu, and to implement preferences.

DESCRIPTION OF THE APP:

This app has been designed as a note-taking app where the user can view, add and delete
notes. Three types of menu have been implemented in this app. There is a context menu that
allows you to choose what to do with the newly created notes, i.e., should they be edited or
deleted. A pop-up menu asks if the note is to be saved, or if the user would like to access the
settings. The settings can also be directly accessed when the user selects the option menu. The
user may change also preferences of the app, such as the theme, font, and the title text displayed.

TECHNICAL CONCEPTS STUDIED IN THE EXERCISE:

• Context menu (floating and action mode)


• Options menu
• Pop-up menu
• Shared Preferences Settings

SOURCE CODE:

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

<LinearLayout 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:id="@+id/layout"
android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:background="@color/techie"

tools:context="com.example.nigil.sharedpreferences.MainActivity">

<ImageView

android:id="@+id/img_top"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="20dp"

android:layout_gravity="center"

android:src="@drawable/techie_top"/>

<TextView

android:id="@+id/tv_hello"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:textSize="50dp"

android:text="Hello User!"

/>

<!--<Button

android:id="@+id/btn_settings"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Settings"

android:layout_weight="1"

android:layout_marginBottom="20dp"

android:layout_gravity="center"
android:onClick="goToSettings"/>-->

<Button

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="UPDATE"

android:onClick="showpopup"/>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listview"></ListView>

<!--<ImageView

android:id="@+id/img_bottom"

android:layout_width="match_parent"

android:layout_height="100dp"

android:layout_gravity="end"

android:adjustViewBounds="true"

android:scaleType="fitCenter"

android:src="@drawable/techie_bottom" />-->

</LinearLayout>

</LinearLayout>

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

<fragment xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/activity_settings"

android:name="com.example.anantha.sharedpreferences.SettingsFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

/>
MainActivity.java:
package com.example.nigil.sharedpreferences;

import android.content.SharedPreferences;

import android.graphics.Typeface;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.support.v7.preference.PreferenceManager;

import android.text.SpannableString;

import android.text.style.StyleSpan;

import android.view.ContextMenu;

import android.view.Menu;

import android.view.MenuInflater;

import android.view.MenuItem;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.ListView;

import android.widget.PopupMenu;

import android.widget.TextView;

import android.content.Intent;

import android.view.View;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends AppCompatActivity implements


SharedPreferences.OnSharedPreferenceChangeListener,PopupMenu.OnMenuItemClickL
istener{
ImageView top_image;

TextView tvHello;

ImageView bottom_image;

LinearLayout layout;

ListView listView;

List<String> list = new ArrayList<>();

ArrayAdapter<String> adapter;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

setUpSharedPreferences();

listView = findViewById(R.id.listview);

list.add("Monitor");

list.add("Keyboard");

list.add("Mouse");

list.add("Mother Board");

list.add("Hard Disk");

adapter = new ArrayAdapter<String>(this, android.

R.layout.simple_expandable_list_item_1,list);

listView.setAdapter(adapter);

registerForContextMenu(listView);

// public void goToSettings(View view){

// Intent startSettingsActivity = new


Intent(this,SettingsActivity.class);

// startActivity(startSettingsActivity);

// }
public void setUpSharedPreferences(){

SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(this);

setItalic(sharedPreferences.getBoolean("italicize",true));

setMyTheme(sharedPreferences.getString("theme","nature"));

setMyName(sharedPreferences.getString("name","User"));

sharedPreferences.registerOnSharedPreferenceChangeListener(this);

private void setItalic(boolean b) {

tvHello = findViewById(R.id.tv_hello);

SpannableString spannableString = new


SpannableString(tvHello.getText().toString());

if(b)

spannableString.setSpan(new
StyleSpan(Typeface.ITALIC),0,spannableString.length(),0);

//tvHello.setTypeface(null, Typeface.ITALIC);

else

spannableString.setSpan(new
StyleSpan(Typeface.NORMAL),0,spannableString.length(),0);

//tvHello.setTypeface(null,Typeface.NORMAL);

tvHello.setText(spannableString);

public void setMyTheme(String myTheme) {

top_image = findViewById(R.id.img_top);

// bottom_image = findViewById(R.id.img_bottom);

layout = findViewById(R.id.layout);

if(myTheme.equals("nature")){
top_image.setImageResource(R.drawable.nature_top);

// bottom_image.setImageResource(R.drawable.nature_bottom);

layout.setBackgroundColor(getResources().getColor(R.color.nature));

else if(myTheme.equals("solar")){

top_image.setImageResource(R.drawable.solar_top);

// bottom_image.setImageResource(R.drawable.solar_bottom);

layout.setBackgroundColor(getResources().getColor(R.color.solar));

else if(myTheme.equals("techie")){

top_image.setImageResource(R.drawable.techie_top);

// bottom_image.setImageResource(R.drawable.techie_bottom);

layout.setBackgroundColor(getResources().getColor(R.color.techie));

public void setMyName(String myName){

tvHello.setText("Hello "+myName+ " !");

@Override

public void onSharedPreferenceChanged(SharedPreferences


sharedPreferences, String s) {

if(s.equals("italicize"))

setItalic(sharedPreferences.getBoolean("italicize",true));

if(s.equals("theme")){

setMyTheme(sharedPreferences.getString("theme","nature"));

if(s.equals("name")){
setMyName(sharedPreferences.getString("name","User"));

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_menu,menu);

return true;

public void onCreateContextMenu(ContextMenu menu, View v,


ContextMenu.ContextMenuInfo menuInfo) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.main_context_menu,menu);

public boolean onContextItemSelected(MenuItem item) {

AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

switch(item.getItemId())

case R.id.delete_id:

list.remove(info.position);

adapter.notifyDataSetChanged();

return true;

default: return super.onContextItemSelected(item);

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();
//noinspection SimplifiableIfStatement

Intent startSettingsActivity = new


Intent(this,SettingsActivity.class);

startActivity(startSettingsActivity);

return super.onOptionsItemSelected(item);

@Override

protected void onDestroy() {

PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPrefere
nceChangeListener(this);

super.onDestroy();

public void showpopup(View view) {

PopupMenu popupMenu = new PopupMenu(this,view);

popupMenu.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener)
MainActivity.this);

MenuInflater inflater = popupMenu.getMenuInflater();

inflater.inflate(R.menu.popup_menu, popupMenu.getMenu());

popupMenu.show();

@Override

public boolean onMenuItemClick(MenuItem menuItem) {

switch(menuItem.getItemId())

case R.id.add:

Toast.makeText(getBaseContext(),"You selected
p1",Toast.LENGTH_LONG);

list.add("hari");
adapter.notifyDataSetChanged();

return true;

case R.id.remove:

list.remove(2);

Toast.makeText(getBaseContext(),"You selected
p2",Toast.LENGTH_LONG);

return true;

case R.id.p3:

Intent startSettingsActivity = new


Intent(this,SettingsActivity.class);

startActivity(startSettingsActivity);

Toast.makeText(getBaseContext(),"You selected
p3",Toast.LENGTH_LONG);

return true;

default: return false;

SettingsActivity.java:
package com.example.nigil.sharedpreferences;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.preference.PreferenceManager;

import android.support.annotation.Nullable;

import android.support.v7.app.ActionBar;

import android.support.v7.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_settings);
ActionBar actionBar = this.getSupportActionBar();

if(actionBar != null){

actionBar.setDisplayHomeAsUpEnabled(true);

getSupportFragmentManager().beginTransaction().replace(android.R.id.content,n
ew SettingsFragment()).commit();

// SharedPreferences sharedPref =
PreferenceManager.getDefaultSharedPreferences(this);

SettingsFragment.java:
package com.example.nigil.sharedpreferences;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.support.v7.preference.CheckBoxPreference;

import android.support.v7.preference.EditTextPreference;

import android.support.v7.preference.ListPreference;

import android.support.v7.preference.Preference;

import android.support.v7.preference.PreferenceFragmentCompat;

import android.support.v7.preference.PreferenceScreen;

public class SettingsFragment extends PreferenceFragmentCompat implements


SharedPreferences.OnSharedPreferenceChangeListener {

@Override

public void onCreatePreferences(Bundle savedInstanceState, String


rootKey) {

addPreferencesFromResource(R.xml.pref_settings);

SharedPreferences sharedPreferences =
getPreferenceScreen().getSharedPreferences();

PreferenceScreen preferenceScreen = getPreferenceScreen();


int count = preferenceScreen.getPreferenceCount();

for(int i=0;i<count;i++){

Preference pref = preferenceScreen.getPreference(i);

if(!(pref instanceof CheckBoxPreference)){

String value = sharedPreferences.getString(pref.getKey(),"");

setPreferenceSummary(pref,value);

private void setPreferenceSummary(Preference preference, String value){

if(preference instanceof ListPreference){

ListPreference listPreference = (ListPreference) preference;

int prefIndex = listPreference.findIndexOfValue(value);

if(prefIndex>=0){

listPreference.setSummary(listPreference.getEntries()[prefIndex]);

else if(preference instanceof EditTextPreference){

preference.setSummary(value);

@Override

public void onSharedPreferenceChanged(SharedPreferences


sharedPreferences, String s) {

Preference pref = findPreference(s);

if(pref != null){

if(!(pref instanceof CheckBoxPreference)){


String value =
sharedPreferences.getString(findPreference(s).getKey(),"");

setPreferenceSummary(pref,value);

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChange
Listener(this);

@Override

public void onDestroy() {

super.onDestroy();

getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChan
geListener(this);

RESULT:

The app was created, with the different menu types and shared preferences implemented
successfully.

Vous aimerez peut-être aussi