There are no dividers after switching to PreferenceFragmentCompat - android

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

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>

How to make visible and invisible an image by clicking a button in android studio?

i have two activities in android studio.act1 with a button and act2 with an imageView. i want to click the button in act1 and make the image in act2 visible. and when i click button for second time, this time make the image invisible and do it again and again and again. how can i do that?
you must create this class;
public class PublicSharedPreferences {
public static void setDefaults(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
}
and then learn sharedpreferences enter link description here
Activity1;
public class Activity1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String visibilityStr = PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr != null) {
if (visibilityStr.equals("0")) {
Toast.makeText(Activity1.this, "it visibled", Toast.LENGTH_SHORT).show();
visibilityStr = "1";
} else {
visibilityStr = "0";
Toast.makeText(Activity1.this, "it invisibled", Toast.LENGTH_SHORT).show();
}
} else {
visibilityStr = "1";
Toast.makeText(Activity1.this, "it visibled", Toast.LENGTH_SHORT).show();
}
PublicSharedPreferences.setDefaults("keyVisibility", visibilityStr, getApplicationContext());
Intent intent = new Intent(Activity1.this, Activity2.class);
Activity1.this.startActivity(intent);
}
});
}
}
Activity2;
public class Activity2 extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
ImageView imgView = (ImageView) findViewById(R.id.imgView1);
String visibilityStr = PublicSharedPreferences.getDefaults("keyVisibility", getApplicationContext());
if (visibilityStr.equals("0"))
imgView.setVisibility(View.INVISIBLE);
else
imgView.setVisibility(View.VISIBLE);
}
}
Layout1;
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.c.a.myapplication.Activity1">
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"/>
</LinearLayout>
Layout2;
<?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">
<ImageView
android:id="#+id/imgView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_menu_camera"
android:visibility="invisible"/>
</LinearLayout>
Its work.
Try this code....
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class Sample extends Activity {
ImageView img;
Button btn;
boolean clicked = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
btn = (Button) findViewById(R.id.t1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
clicked = true;
Intent intent = new Intent(Sample.this, Dample.class);
intent.putExtra("value", true);
startActivity(intent);
}
});
}
}
//Dample.class In second activity
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
public class Dample extends Activity {
ImageView img;//use image view
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pimple);
img= (ImageView) findViewById(R.id.t1);
Boolean yourBool = getIntent().getExtras().getBoolean("value");
if (yourBool == true) {
img.setVisibility(View.VISIBLE);///use visibility code for imageview as mentioned above
}
}
}

Main activity Layout overlays SettingsActivity

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

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads the below lines

The MainActivity file
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
I am getting this error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: minor_activities.Status cannot be cast to com.example.intel.dualboot.MainFragment
at com.example.intel.dualboot.MainFragment.newFragment(MainFragment.java:28)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
here is your error...
android.support.v4.widget.SwipeRefreshLayout cannot be cast to com.example.intel.dualboot.InSwipeRefreshLayout
You have initialize SwipeToRefresh in XML as "android.support.v4.widget.SwipeRefreshLayout" But you are trying to create object of that view as "com.example.intel.dualboot.InSwipeRefreshLayout". So you got an error because of wrong casting of class. Change "android.support.v4.widget.SwipeRefreshLayout" to "com.example.intel.dualboot.InSwipeRefreshLayout" in xml to solve your problem.

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.

Categories

Resources