Main activity Layout overlays SettingsActivity - android

I am currently trying to develop an android application which should have Settings. How far I am informed I should use a SettingsActivity.
Mine looks currently like this:
package de.nocompany.myname.gw2companion;
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.*;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.ViewGroup;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) getResources().getDimension(R.dimen.activity_vertical_margin) + 30, getResources().getDisplayMetrics());
getListView().setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);
}
private void setupActionBar() {
getLayoutInflater().inflate(R.layout.app_bar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
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);
}
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);
}
#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);
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);
}
}
#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);
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);
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class DataSyncPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
setHasOptionsMenu(true);
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);
}
}
}
The problem with this code is, that my preferences are not practically usable, because my MainActivity layout is shown above the settings. I have searched a lot for this, but still I cannot find an answer which satisfies my needs. A lot of guys said that you could use wrap the SettingsActivity with Layouts and Stuff, but to my knowledge this is not Good Practice programming which I am trying to do. And I know this is pretty near at the Google example, but I am currently starting to develop the application so this will be replaced! Thx in advance!
EDIT: Replaced the code with the new issue.

Yeah this is an annoying one! I ran into the same issue - The pattern used on the Android Developer site is dated to the days of API 10. My example below demonstrates how to implement Preferences using a modern Activity/Fragment design pattern.
pref_general.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:icon="#drawable/ic_sort_black_48dp"
android:title="#string/pref_sort_label"
android:key="#string/pref_sort_key"
android:defaultValue="#string/pref_sort_favorite"
android:entryValues="#array/pref_sort_values"
android:entries="#array/pref_sort_options" />
</PreferenceScreen>
arrays.xml
<resources>
<string-array name="pref_sort_options">
<item>#string/pref_sort_label_popular</item>
<item>#string/pref_sort_label_rating</item>
<item>#string/pref_sort_label_favorite</item>
</string-array>
<string-array name="pref_sort_values">
<item>#string/pref_sort_popular</item>
<item>#string/pref_sort_rating</item>
<item>#string/pref_sort_favorite</item>
</string-array>
</resources>
strings.xml
<string name="pref_sort_label">Sort Order</string>
<string name="pref_sort_label_popular">Most Popular</string>
<string name="pref_sort_label_rating">Top Rated</string>
<string name="pref_sort_label_favorite">Favorites</string>
<string name="pref_sort_key" translatable="false">sort</string>
<string name="pref_sort_popular" translatable="false">popular</string>
<string name="pref_sort_rating" translatable="false">rating</string>
<string name="pref_sort_favorite" translatable="false">favorites</string>
activity_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context=".SettingsActivity"
tools:ignore="MergeRootFrame">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<FrameLayout
android:id="#+id/container_settings"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
app_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ToolbarTheme"
android:elevation="4dp"
app:titleMarginStart="32dp"
app:popupTheme="#style/PopupTheme">
</android.support.v7.widget.Toolbar>
SettingsActivity.java
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getFragmentManager().beginTransaction()
.replace(R.id.container_settings, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener {
public static String TAG = SettingsFragment.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_sort_key)));
}
private void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
}
else {
preference.setSummary(stringValue);
}
return true;
}
}
}

I found my failure! After reading apelosoczi's answer I found out that in my app bar, I had an include with my main layout. Now after I declared my own app_bar for this it works! But now I have to add padding over the subsettings :( which does not work currently]1

Related

Toolbar overlaps the PreferenceFragment

As you see in the title, The toolbar appears, but it overlaps my preferenceFragment content.
I fixed the issue on the Settings Screen by adding a padding to the listview.
But the problem persists in all the other preferenceFragments. Here is my code.
Activity
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
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);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ClassFragment()).commit();
PreferenceManager.setDefaultValues(this,
R.xml.pref_students, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_information, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_security, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notifications, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_logout, false);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addStudent:
displayToast(getString(R.string.action_addStudent_message));
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_class:
selectedFragment = new ClassFragment();
break;
case R.id.navigation_due:
selectedFragment = new DueFragment();
break;
case R.id.navigation_messages:
selectedFragment = new MessagesFragment();
break;
case R.id.navigation_class_updates:
selectedFragment = new ClassUpdatesFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
SettingsActivity
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.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;
import androidx.recyclerview.widget.RecyclerView;
import com.example.schooltest.Settings.AppCompatPreferenceActivity;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
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;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(
sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener
.onPreferenceChange(preference, PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) getResources().getDimension(R.dimen.activity_vertical_margin) + 30, getResources().getDisplayMetrics());
getListView().setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);
}
private void setupActionBar() {
getLayoutInflater().inflate(R.layout.settings_toolbar, (ViewGroup)findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
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);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| StudentsPreferenceFragment
.class.getName().equals(fragmentName)
|| InformationPreferenceFragment
.class.getName().equals(fragmentName)
|| SecurityPreferenceFragment
.class.getName().equals(fragmentName)
|| NotificationsPreferenceFragment
.class.getName().equals(fragmentName)
|| LogoutPreferenceFragment
.class.getName().equals(fragmentName);
}
/**
* This fragment shows student preferences only.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class StudentsPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_students);
setHasOptionsMenu(true);
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);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
/**
* This fragment shows information preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class InformationPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_information);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("first_name"));
bindPreferenceSummaryToValue(findPreference("last_name"));
bindPreferenceSummaryToValue(findPreference("example_text"));
}
#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 security preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class SecurityPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_security);
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 notifications preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationsPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
setHasOptionsMenu(true);
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 logout preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class LogoutPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_logout);
setHasOptionsMenu(true);
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);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#FFFFFF"
app:popupTheme="#style/AppTheme.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</RelativeLayout>
As you see in this photo, the "First Name" EditTextPreference is hidden by the toolbar:
I think, maybe it has something to do with the preference ressource files under xml/. so here a link to the files : https://github.com/waeljomni/apptest.git
The problem here is that you are inflating the activity_main.xml layout in android.R.id.content and the preference fragments into com.android.internal.R.id.headers (if you see the implementation of PreferenceActivity).
The default XML layout of PreferenceActivity is preference_list_content.
You should define in your team your custom preference layout in which you reproduce your main Activity layout.
See headerLayout in R.attr.preferenceActivityStyle.
I suggest to use ConstraintLayout for performance reason and simplicity
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.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:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
app:popupTheme="#style/AppTheme.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

There are no dividers after switching to PreferenceFragmentCompat

I can't add dividers between preferences also can't set padding in PreferenceFragmentCompat
I was trying to switch from PreferenceFragment to PreferenceFragmentCompat almost everything work fine, but I can't add dividers between preferences also can't set padding
My Settings and MainPreferenceFragment .java files:
import android.content.*;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.*;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
public class SettingsActivity extends AppCompatActivity implements SharedPreferences
.OnSharedPreferenceChangeListener
{
private SharedPreferences sharedPrefs;
private static StitchAppClient client = Stitch.getDefaultAppClient();
private static int clickCounter = 0;
private static final String LOG_TAG = SettingsActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
// Get ActionBar and display LOGO {{
ActionBar actionBar = getSupportActionBar();
try {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
} catch (Exception e) {
Log.e(LOG_TAG,"Error " + e.getMessage());
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// register preference change listener
sharedPrefs.registerOnSharedPreferenceChangeListener(this);
}
public static class MainPreferenceFragment extends PreferenceFragmentCompat implements Preference
.OnPreferenceChangeListener
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_main);
//if preference has changed it shows the value in summary of onChange_Color
Preference onChange_Color = findPreference(getString(R.string
.settings_change_color_key));
bindPreferenceSummaryToValue(onChange_Color);
String clientID = client.getAuth().getUser().getId();
Preference user_id = findPreference("user_id");
user_id.setSummary(clientID);
try{
user_id.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener(){
#Override
public boolean onPreferenceClick(Preference preference) {
clickCounter ++;
if(clickCounter==3){
setIDasClipData(getActivity(),clientID);
clickCounter=0;
}
return true;
}
});
}catch (Exception e){
Log.e(LOG_TAG," Error: " + e);
}
SwitchPreferenceCompat soundSwitch = (SwitchPreferenceCompat) findPreference("pref_sound");
if (soundSwitch != null) {
if (soundSwitch.isChecked()) {
soundSwitch.setTitle(getString(R.string.turn_off_the_sound));
} else {
soundSwitch.setTitle(getString(R.string.turn_on_the_sound));
}
soundSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object isSoundOnObject) {
boolean isVibrateOn = (Boolean) isSoundOnObject;
if (isVibrateOn) {
soundSwitch.setTitle(getString(R.string.turn_off_the_sound));
} else {
soundSwitch.setTitle(getString(R.string.turn_on_the_sound));
}
return true;
}
});
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//HERE CAN'T SET LIST DIVIDERS
setDivider(getResources().getDrawable(R.drawable.list_divider));
setDividerHeight(4);
}
#Override
public void onCreatePreferences(Bundle bundle, String s) {
}
private static void setIDasClipData(Context c,String textToCopy){
final ClipboardManager clipboardManager =(ClipboardManager) c.getSystemService(CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("", textToCopy);
clipboardManager.setPrimaryClip(clipData);
Toast ToastMessage = Toast.makeText(c, c.getString(R.string.client_id_been_copied_to_tray), Toast.LENGTH_LONG);
View toastView = ToastMessage.getView();
toastView.setBackgroundResource(R.drawable.toast_custom);
ToastMessage.show();
}
//help Method
private void bindPreferenceSummaryToValue(Preference preference)
{
preference.setOnPreferenceChangeListener((Preference.OnPreferenceChangeListener) this);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences
(preference.getContext());
String preferenceString = preferences.getString(preference.getKey(), "");
onPreferenceChange(preference, preferenceString);
}
//If preference has changed
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
//if preference instanceof ListPreference set summary to this
if (preference instanceof ListPreference)
{
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0)
{
CharSequence[] labels = listPreference.getEntries();
preference.setSummary(labels[prefIndex]);
}
//else set summary to String value
}
else
{
preference.setSummary(stringValue);
}
return true;
}
}
/*
* making a menu code
*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.top_icons_settings, menu);
return true;
}
#Override
public boolean onSupportNavigateUp()
{
onBackPressed();
Intent mainIntent = new Intent(this, MainActivity.class);
startActivity(mainIntent);
return true;
}
}
settings_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="title">
<android.support.v7.preference.ListPreference
android:dialogTitle="#string/settings_color_label"
android:defaultValue="#string/settings_change_color_default"
android:entries="#array/settings_color_label"
android:entryValues="#array/settings_color_values"
android:key="#string/settings_change_color_key"
android:title="#string/settings_color_label"
/>
<android.support.v7.preference.SwitchPreferenceCompat
android:key="pref_sound"
android:title="#string/turn_off_the_sound"
android:defaultValue="true" />
<android.support.v7.preference.Preference
android:title="#string/user_id_settings"
android:key="user_id"
android:summary="---">
</android.support.v7.preference.Preference>
<android.support.v7.preference.Preference
android:title="#string/program_version"
android:key="program version"
android:summary="1.0">
</android.support.v7.preference.Preference>
<android.support.v7.preference.PreferenceScreen
android:title="#string/privacy_policy_title"
android:summary="#string/privacy_policy_tap_toopen">
<android.support.v7.preference.Preference
android:key="privacy"
android:title="#string/privacy_policy_title"
android:summary="#string/privacy_policy_summary"/>
</android.support.v7.preference.PreferenceScreen>
</android.support.v7.preference.PreferenceScreen>
settings_fragment.xml :
<?xml version="1.0" encoding="utf-8"?>
<fragment
android:id="#+id/settings_activity_fragment"
android:name="project.ironmax.com.ironmax_guard.SettingsActivity$MainPreferenceFragment"
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"
tools:context="project.ironmax.com.ironmax_guard.SettingsActivity"
android:clickable="true"
android:background="#drawable/ripple">
</fragment>
Want to make padding and dividers appear

Up navigation to swap between activities doesn't work

My app basicly contains two activities, a main-activity and a settings-activity.
Settings-activity is launched by
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
, which contains some fragments. I use the up navigation, which works perfectly in settings-activity between the fragments, but however I don't return to my main-activity when pressing the back button. The setDisplayHomeAsUpEnabled command is in my settings-activity, bc it didn't helped to solve my problem when I positioned it in my main-activity.
In my manifest I've declared main-activity as the parent activity for settings-activity.
So what do I have to do? - lot's of thanks!
My Mainactivity
package user.example;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent launchNewIntent = new Intent(MainActivity.this,SettingsActivity.class);
startActivityForResult(launchNewIntent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
My SettingsActivity: (I've left out the fragments, but the same error is reproduced)
package user.example;
import android.support.v7.app.ActionBar;
public class SettingsActivity extends AppCompatPreferenceActivity {
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#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);
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);
}
}
}
AppCompatPreferenceActivity: (started by Settings.activity)
package user.example;
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;
}
}
I figured out that I had to put this code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
into my AppCompatPreferenceActivity.java, now everything wokrs, thanks for all help so far!!! :)
I think you need to set the "main Activity" as the Parent Activity to "Settings Activity" in the Mainfest like that
<activity android:name=".SettingActivity"
android:parentActivityName=".MainActivity"></activity>
Edit
You neeed to add in the Setting Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

nav drawer design support

navigation drawer not responding to clicks and snack is also not showing up.
how to make the clicks responsive and add fragments for data loading.
their are two items in the drawer and only one gets checked at the time of selection.
package com.example.jasaran.nav;
import com.example.jasaran.nav.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
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.FrameLayout;
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
private FrameLayout mContentFrame;
private int mCurrentSelectedPosition;
private static final String PREFERENCES_FILE = "nav_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
int mselected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpToolbar();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
boolean mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_launcher);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mselected = menuItem.getItemId();
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
Snackbar.make(mContentFrame, "Item One", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
return true;
case R.id.navigation_item_2:
Snackbar.make(mContentFrame, "Item Two", Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
}
I see you've implemented the listener directly from the Activity. Try attaching it to the NavigationView like this:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle menu clicks here
}
});
Check this Activity code on GitHub.

How to dynamically add user input into a listView within a fragment?

Im trying to add text into a listview within a fragment but i keep getting an error: cannot find symbol method setListAdapter(ArrayAdapter).
I'm using this tutorial as reference but it only shows how to do it within a activity : http://wptrafficanalyzer.in/blog/dynamically-add-items-to-listview-in-android/
Im trying to move this over to a fragment. Can anyone help please i would highly appreciate it? heres my code :
MainActivity:
import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import com.example.fragments.DeleteDialogueFragment;
import com.example.PeopleFragment;
public class MainActivity extends Activity implements PeopleFragment.PeopleFragmentListener, DeleteDialogueFragment.DeleteDialogueListener {
private final String TAG = "MAINACTIVITY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PeopleFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//INTERFACE METHODS
public void deleteCharacter(){
PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentById(R.id.container);
peopleFragment.deleteCharacter();
}
}
PeopleFragment :
import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.example.actionbardemo.R;
import java.util.ArrayList;
import java.util.Arrays;
public class PeopleFragment extends Fragment{
private final String TAG = "PEOPLEFRAGMENT";
private PeopleFragmentListener mListener;
private ArrayAdapter<String> mPeopleAdapter;
private ActionMode mActionMode;
private int mPersonSelected = -1;
/** Items entered by the user is stored in this ArrayList variable */
private ArrayList<String> pList = new ArrayList<String>();
public interface PeopleFragmentListener {
}
public static PeopleFragment newInstance() {
PeopleFragment fragment = new PeopleFragment();
return fragment;
}
public PeopleFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> people = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.people)));
mPeopleAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,people);
// Reference to the button of the layout main.xml
Button btn = (Button) getView().findViewById(R.id.btnAdd);
// Defining a click event listener for the button "Add"
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) getView().findViewById(R.id.txtItem);
pList.add(edit.getText().toString());
edit.setText("");
mPeopleAdapter.notifyDataSetChanged();
}
};
// Setting the event listener for the add button
btn.setOnClickListener(listener);
// Setting the adapter to the ListView
setListAdapter(mPeopleAdapter);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView peopleList = (ListView) rootView.findViewById(R.id.peopleList);
peopleList.setAdapter(mPeopleAdapter);
peopleList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if(mActionMode != null){
return false;
}
mPersonSelected = position;
mActionMode = getActivity().startActionMode(mActionModeCallback);
return true;
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (PeopleFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement PeopleFragmentListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
//INTERFACE METHODS
public void deleteCharacter(){
mPeopleAdapter.remove(mPeopleAdapter.getItem(mPersonSelected));
mPeopleAdapter.notifyDataSetChanged();
}
public String getToDelete(){
return mPeopleAdapter.getItem(mPersonSelected);
}
//CONTEXTUAL ACTION BAR CALLBACK
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.peoplemenu, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.peopleDelete:
Log.i(TAG,mPeopleAdapter.getItem(mPersonSelected));
DialogFragment dialog = new DeleteDialogueFragment();
Bundle args = new Bundle();
args.putString("name",mPeopleAdapter.getItem(mPersonSelected));
dialog.setArguments(args);
dialog.show(getActivity().getFragmentManager(), "DeleteDiaglogueFragment");
mode.finish();
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
activity_main.xml (layout):
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />
fragment_main.xml (layout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/txtItem"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/hintTxtItem"/>
<Button
android:id="#+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/lblBtnAdd"
android:layout_toRightOf="#id/txtItem"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/peopleList"
android:layout_gravity="center_horizontal" />
</LinearLayout>
strings.xml(values):
<string name="app_name">ActionBarDemo</string>
<string name="action_settings">Settings</string>
<string name="hintTxtItem">Enter an item here ...</string>
<string name="lblBtnAdd">Add Item</string>
<string name="txtEmpty">List is empty</string>
<string name="delete_confirm">Are you sure you want to delete</string>
<string name="delete">Delete</string>
<string name="cancel">Cancel</string>
<string-array name="people">
<item>person 1</item>
<item>person 2</item>
<item>person 3</item>
<item>person 4</item>
<item>person 5</item>
<item>person 6</item>
</string-array>

Categories

Resources