How to get toolbar in my PreferenceActivity - android

I've been trying to get a Toolbar to show up in my PreferenceActivity following the answer from Gabor using AppCompatPreferenceActivity shown here: Creating a Preference Screen with support (v21) Toolbar . However I can not get it to work. my code:
Settings.java:
public class Settings extends AppCompatPreferenceActivity{
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preferences, target);
setContentView(R.layout.settings_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setHomeButtonEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setDisplayShowTitleEnabled(true);
bar.setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
bar.setTitle("Test2");
}
#Override
protected boolean isValidFragment(String fragmentName) {
return MyPreferenceFragment.class.getName().equals(fragmentName);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
public static class MyPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Preference removeMedalsButton = findPreference("removeMedals");
removeMedalsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Medailles verwijderd",Toast.LENGTH_SHORT).show();
removeMedals(getActivity());
return true;
}
});
Preference removeWorkoutsButton = findPreference("removeWorkouts");
removeWorkoutsButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Workouts verwijderd",Toast.LENGTH_SHORT).show();
removeWorkouts();
return true;
}
});
Preference removeProfileButton = findPreference("removeProfile");
removeProfileButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Toast.makeText(getActivity(),"Profiel verwijderd",Toast.LENGTH_SHORT).show();
removeProfile();
return true;
}
});
}
}
public static void removeMedals(Context context){
AchievementTracker.removeMedals(context);
}
public static void removeWorkouts(){
}
public static void removeProfile(){
}
}
settings_page.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:orientation="vertical"
android:padding="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ToolbarTheme"/>
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
preference.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:title="#string/reminder_preference"
android:defaultValue="false"
android:summary="#string/reminder_preference_summary"
android:key="reminderPreference" />
<Preference android:title="#string/remove_medals"
android:key="removeMedals"
android:summary="#string/remove_medals_summary"/>
<Preference android:title="#string/remove_profile"
android:key="removeProfile"
android:summary="#string/remove_profile_summary"/>
<Preference android:title="#string/remove_workouts"
android:key="removeWorkouts"
android:summary="#string/remove_workouts_summary"/>
</PreferenceScreen>
The error i'm getting is:
XML document must start with <preference-headers> tag; foundPreferenceScreen at Binary XML file line #2
I think it's because i'm calling setContentView(R.Layout.settings_page) but that's how i'm supposed to do this according to Gabor's answer.

Related

Load Preferences Settings in Swipable Tabs with Fragment

I have searched the web but didnt find any proper solution.
I am trying to load some preference Settings in Tab Fragments.
In the first Image, When I use menu Inflator, I get those 3 dotted buttons, I dont need those, insted I want the menu to load in my Tab Fragment.
Below is the code of my
SettingPrefActivity.java
public class SettingsPrefActivity extends AppPreferenceActivity {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// load settings fragment
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
}
public static class MainPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_main);
// gallery EditText change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));
// notification preference change listener
bindPreferenceSummaryToValue(findPreference(getString(R.string.key_notifications_new_message_ringtone)));
// feedback preference click listener
Preference myPref = findPreference(getString(R.string.key_send_feedback));
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
sendFeedback(getActivity());
return true;
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.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(R.string.summary_choose_ringtone);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else if (preference instanceof EditTextPreference) {
if (preference.getKey().equals("key_gallery_name")) {
// update the changed gallery name to summary filed
preference.setSummary(stringValue);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
};
/**
* Email client intent to send support mail
* Appends the necessary device information to email body
* useful when providing support
*/
public static void sendFeedback(Context context) {
String body = null;
try {
body = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
body = "\n\n-----------------------------\nPlease don't remove this information\n Device OS: Android \n Device OS version: " +
Build.VERSION.RELEASE + "\n App Version: " + body + "\n Device Brand: " + Build.BRAND +
"\n Device Model: " + Build.MODEL + "\n Device Manufacturer: " + Build.MANUFACTURER;
} catch (PackageManager.NameNotFoundException e) {
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact#androidhive.info"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Query from android app");
intent.putExtra(Intent.EXTRA_TEXT, body);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.choose_email_client)));
}}
SettingsActivity.java
public class SettingsActivity extends Fragment {
private static final String TAG = SettingsPrefActivity.class.getSimpleName();
/*public SettingsActivity() {
// Required empty public constructor
}*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.setting_layout, container, false);
}
/*public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// launch settings activity
startActivity(new Intent(SettingsActivity.this, SettingsPrefActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
pref_main.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="General">
<EditTextPreference
android:defaultValue="#string/default_gallery_storage"
android:key="#string/key_gallery_name"
android:summary="#string/default_gallery_storage"
android:title="#string/title_gallery_storage" />
<CheckBoxPreference
android:defaultValue="true"
android:key="#string/key_upload_over_wifi"
android:summary="#string/summary_upload_over_wifi"
android:title="#string/title_auto_upload" />
<ListPreference
android:defaultValue="3"
android:dialogTitle="#string/title_upload_quality"
android:entries="#array/pref_upload_quality_entries"
android:entryValues="#array/pref_upload_quality_values"
android:key="#string/key_upload_quality"
android:summary="#string/summary_upload_video_quality"
android:title="#string/title_upload_quality" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_title_notifications">
<SwitchPreference
android:defaultValue="true"
android:key="#string/notifications_new_message"
android:title="#string/title_new_notification_sound" />
<RingtonePreference
android:defaultValue="content://settings/system/notification_sound"
android:dependency="notifications_new_message"
android:key="#string/key_notifications_new_message_ringtone"
android:ringtoneType="notification"
android:summary="#string/summary_choose_ringtone"
android:title="#string/pref_title_ringtone" />
<SwitchPreference
android:defaultValue="true"
android:key="#string/key_vibrate"
android:summary="#string/summary_vibrate"
android:title="#string/title_vibrate" />
</PreferenceCategory>
<PreferenceCategory android:title="#string/pref_header_about">
<Preference
android:selectable="false"
android:summary="#string/summary_about" />
<Preference
android:summary="#string/app_version"
android:title="#string/title_version" />
<Preference
android:key="#string/key_send_feedback"
android:summary="#string/summary_support"
android:title="#string/title_send_feedback" />
<!-- preference opens url in browser -->
<Preference
android:summary="#string/summary_faq"
android:title="#string/title_faq">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_faq" />
</Preference>
<Preference android:title="#string/privacy_policy">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_privacy" />
</Preference>
<Preference android:title="#string/title_terms">
<intent
android:action="android.intent.action.VIEW"
android:data="#string/url_terms" />
</Preference>
</PreferenceCategory>
</PreferenceScreen>
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu 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"
tools:context="settings.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
settings_layout.xml
<RelativeLayout 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Settings Page!! Coming Soon!"
android:textSize="30dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {R.drawable.ic_action_name};
String[] tabTitle={"","All"};
int[] unreadCount={0,5,3,0,12,3,9,0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
setupTabIcons();
}
private View prepareTabView(int pos) {
View view = getLayoutInflater().inflate(R.layout.custom_tab,null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_count = (TextView) view.findViewById(R.id.tv_count);
tv_title.setText(tabTitle[pos]);
if(unreadCount[pos]>0)
{
tv_count.setVisibility(View.VISIBLE);
tv_count.setText(""+unreadCount[pos]);
}
else
tv_count.setVisibility(View.GONE);
return view;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
for(int i = 1; i < unreadCount.length; i++)
{
/*TabLayout.Tab tabitem = tabLayout.newTab();
tabitem.setCustomView(prepareTabView(i));
tabLayout.addTab(tabitem);*/
tabLayout.getTabAt(i).setCustomView(prepareTabView(i));
}
}
private TabLayout.OnTabSelectedListener onTabSelectedListener(final
ViewPager viewPager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SettingsActivity(), "");
adapter.addFragment(new AllTab(), "All");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="inc.apperz.passmanager.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorGreen"
app:tabTextColor="#color/colorWhite"
app:tabIndicatorColor="#color/colorWhite"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.constraint.ConstraintLayout>
Is there any possibility that I can include my main_menu.xml into my setting_layout.xml? such that it will get bind to my SettingsActivity.java?
If its possible, that would be great, but I tried that way and didn't find appropriate way to include it.
Can someone guide me to how to achieve this..
Try adding this to your fragment:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(false);
super.onPrepareOptionsMenu(menu);
return true;
}

Fullscreen Dialog Fragment not showing correctly

I've got two problems:
In my app I have an activity with the appbar and a recycler view.
When i click an option of the floating action menu it displays a Fullscreen Dialogfragment but for some reason the dialog is not showing correctly (not totaly fullscreen).
Here is the result
dialogfragment
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
What should I do. I am beginning Android.
also I want to establish a margin for the cardview (left and right)
Here is my code
Result_contract.java
public class Result_contract extends AppCompatActivity implements
FragmentActions{
String TAG="Result_contract";
private boolean first_time= true;
private List<Contract>lista_contratos;
private FloatingActionsMenu fabm;
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_contract);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Contratos");//Set title
getSupportActionBar().setDisplayHomeAsUpEnabled(true);//Enable Back button
fabm= (FloatingActionsMenu)findViewById(R.id.menu_fab);
View fab_buscar = findViewById(R.id.accion_buscar);
fab_buscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showSearchDialog();
}
});
View fab_formulario = findViewById(R.id.accion_formulario);
fab_formulario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDetailsDialog(0);
}
});
recycler = (RecyclerView) findViewById(R.id.reciclador);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
//todo REMOVER ESTO
//SearchContractTask buscar = new SearchContractTask(Contract_query_instance.getInstance().getContractQuery());
//buscar.execute();
SearchContractTask buscar = new SearchContractTask(null);
buscar.execute();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void showDetailsDialog(int position) {
fabm.collapse();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment fragment=new Dialog_contract();
Bundle args=new Bundle();
args.putInt("position",position);
fragment.setArguments(args);
transaction.add(android.R.id.content, fragment,"dialog_contract").addToBackStack(null).commit();
}
#Override
public void showSearchDialog() {
fabm.collapse();
}
#Override
public void load_data() {
}
public class SearchContractTask extends AsyncTask<Void, Void, Void> {
Connection cnx;
Models models;
Contract_query query;
public SearchContractTask(Contract_query query) {
super();
cnx = Connection.getConnection();
models= Models.getInstance();
this.query=query;
}
#Override
protected Void doInBackground(Void... voids) {
lista_contratos=Contract_list.getInstance().getList_contract();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (lista_contratos!=null) {
adapter = new Contract_adapter(lista_contratos);
recycler.setAdapter(adapter);
}
else {
//TODO MOSTRAR UN MENSAJE DE QUE NO EXISTEN FILAS EN LA CONSULTA
}
}
#Override
protected void onCancelled() {
}
}
#Override public boolean dispatchTouchEvent(MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (fabm.isExpanded()) {
Rect outRect = new Rect();
fabm.getGlobalVisibleRect(outRect);
if(!outRect.contains((int)event.getRawX(), (int)event.getRawY()))
fabm.collapse();
}
}
return super.dispatchTouchEvent(event);
}
#Override
public void onBackPressed() {
if (fabm.isExpanded()) {
fabm.collapse();
}
else{
finish();
}
//super.onBackPressed();
}
}
activity_reult_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.ernesto.apptranscargo.Result_contract">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_result_contract" />
<com.getbase.floatingactionbutton.FloatingActionsMenu
android:id="#+id/menu_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
app:fab_labelStyle="#style/Etiquetas"
app:fab_addButtonColorNormal="?attr/colorPrimary"
app:fab_addButtonSize="normal"
app:fab_labelsPosition="left">
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_formulario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_tablet"
app:fab_size="normal"
app:fab_title="Formulario" />
<com.getbase.floatingactionbutton.FloatingActionButton
android:id="#+id/accion_buscar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fab_colorNormal="?attr/colorAccent"
app:fab_icon="#drawable/ic_search"
app:fab_size="normal"
app:fab_title="Nueva Búsqueda" />
</com.getbase.floatingactionbutton.FloatingActionsMenu>
</android.support.design.widget.CoordinatorLayout>
content_result_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/reciclador"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp"
android:layout_marginTop="20dp"
android:scrollbars="vertical" />
Dialog_contract.java
public class Dialog_contract extends DialogFragment implements DialogActions {
public static final String TAG = "fragment_dialog";
private TabLayout Tabs;
private Form_contract_detail fragment_detalles;
private Form_contract_observation fragment_obseration;
private Fragment fragment_observation;
View view_contract;
ViewPager pager;
PagerAdapter pagerAdapter;
Toolbar toolbar;
String title="Detalles ";
int cantidad;
public Dialog_contract(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void Dismiss()
{
getDialog().dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
cantidad= Contract_list.getInstance().getList_contract().size();
view_contract=inflater.inflate(R.layout.dialog_contract, container, false);
pager=(ViewPager)view_contract.findViewById(R.id.pager);
pagerAdapter= new Dialog_contract_adapter(getActivity(), getChildFragmentManager(),Contract_list.getInstance().getList_contract().size());
toolbar = (Toolbar) view_contract.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(android.R.drawable.ic_menu_close_clear_cancel);
}
setHasOptionsMenu(true);
int position=getArguments().getInt("position", -1);
pager.setAdapter(pagerAdapter);
pager.setPageTransformer(true, new ZoomOutPageTransformer());
//pager.setPageTransformer(true,new DepthPageTransformer() );
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
updateTitle();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
updateTitle();
return view_contract;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
return dialog;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.dialog_contract_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_next) {
pager.setCurrentItem(pager.getCurrentItem() + 1);
updateTitle();
return true;
} else if (id==R.id.action_previous)
{
pager.setCurrentItem(pager.getCurrentItem() - 1);
updateTitle();
return true;
}
else if (id == android.R.id.home) {
// handle close button click here
dismiss();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void updateTitle() {
toolbar.setTitle(title+String.valueOf(pager.getCurrentItem()+1)+"/"+cantidad);
}
}
dialog_contract.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="24dp"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:fitsSystemWindows="false"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:fitsSystemWindows="false"/>
</android.support.design.widget.AppBarLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"/>
</android.support.v4.view.ViewPager>
</LinearLayout>
First of all your dialog layout has top padding so that why it has no full height.
dialog_contract.xml
<android.support.design.widget.CoordinatorLayout
...
android:paddingTop="24dp"
>
Second of all try following java naming convention since your code is realy hard to read
Also when I click the close button of the Dialog it closes not only the dialog, but the activity as well, and goes to the previous activity.
My best guess is that you are not handling menu clicks correctly, try calling
setHasOptionsMenu(true);
from dialogFragmen onCreate

Access EditText Preference dialog box

I'm confused on where I should I place this code using sharedPreferences. I'm trying to find out how the dialog box gets created. I want to access the EditTextPreference dialog box and once the user inputs their name I want to save it to a file using this code below
SharedPreferences mySharedPreferences = getSharedPreferences("MyData",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("user_name",userName.getText().toString());
editor.commit();
Here is my main activity
public class MainActivity extends AppCompatActivity {
EditText userName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Button myButton = (Button) findViewById(R.id.show_button_id);
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
}
});
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(MainActivity.this,UserPreferenceActivity.class);
startActivity(i);
//return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my UserPreferenceFragment java class
public class UserPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//LOAD THE PRFERENCE FROM AN XML RESOURCE FILE
addPreferencesFromResource(R.xml.preferences);
}//ends OnCreate
}
here is my UserPreferenceActivity java class
public class UserPreferenceActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
setContentView(R.layout.content_main);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.
*/
getFragmentManager().beginTransaction()
.replace(android.R.id.content,new UserPreferenceFragment())
.commit();
}
here is my preferences xml file
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="show_background_pic"
android:title="#string/show_background_pic_title"
android:summary="#string/show_background_pic_summary"
android:defaultValue="true">
</CheckBoxPreference>
<EditTextPreference
android:key="user_name"
android:title="#string/user_acct_name_title"
android:summary="#string/user_acct_name_summary"
android:defaultValue="NONAME">
</EditTextPreference>
Lastly my main content
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/Shared_preferences_label"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_button_label"
android:id="#+id/show_button_id"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true" />
</RelativeLayout>
Using setOnPreferenceChangeListener method of Preference class and Preference.OnPreferenceChangeListener interface. something like this:
pref_general.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:capitalize="words"
android:defaultValue="#string/pref_default_display_name"
android:inputType="textCapWords"
android:key="#string/key_example_text"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="#string/pref_title_display_name" />
</PreferenceScreen>
SettingPreferenceFragment.java:
public class SettingPreferenceFragment extends PreferenceFragment {
public final String TAG = "SettingActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
EditTextPreference location = (EditTextPreference) findPreference("example_text");
location.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String locstr = newValue.toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("example_text", locstr);
editor.commit();
Log.e(TAG, "" + locstr);
return true;
}
});
return view;
}
}

Toolbar is hidden in nested PreferenceScreen

I use PreferenceFragment in ActionBarActivity from support-v7 library.
In the Activity I have Toolbar. Everything goes okay, until I open a nested PreferenceScreen.
In the opened screen the Toolbar is hidden.
Maybe somebody know a workaround for this issue?
Preferences xml-file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Main category" >
<EditTextPreference
android:defaultValue="defaultValue"
android:key="key_global_setting"
android:title="Global title" />
</PreferenceCategory>
<PreferenceCategory android:title="Nested screens" >
<PreferenceScreen
android:persistent="false"
android:title="#string/settings_facility_title" >
<CheckBoxPreference
android:defaultValue="false"
android:key="nested_screen_1_1"
android:title="Nested screen 1.1 check box" />
<CheckBoxPreference
android:defaultValue="true"
android:key="nested_screen_1_2"
android:title="Nested screen 1.2 check box" />
</PreferenceScreen>
<PreferenceScreen
android:persistent="false"
android:title="#string/settings_menu_screen_title" >
<CheckBoxPreference
android:defaultValue="true"
android:key="nested_screen2"
android:title="Nested screen 2 check box" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SettingsScreen" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
style="#style/Toolbar" />
<FrameLayout
android:id="#+id/contentSettings"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
I found the solution on my own. I used a small work-around of all this nested PreferenceScreen's. I simply made a separation to different xml-preference files, created an additional Fragment which extends PreferenceFragment and there I show an appropriate nested preference screen.
Maybe somebody would found this useful.
Github sources link.
Some code examples below:
main_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Main category" >
<EditTextPreference
android:defaultValue="defaultValue"
android:key="key_global_setting"
android:title="Global title" />
</PreferenceCategory>
<PreferenceCategory android:title="Nested screens" >
<Preference
android:key="NESTED_KEY1"
android:persistent="false"
android:title="Nested screen #1" />
<Preference
android:key="NESTED_KEY2"
android:persistent="false"
android:title="Nested screen #2" />
</PreferenceCategory>
</PreferenceScreen>
nested_screen1_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Nested screen #1" >
<CheckBoxPreference
android:defaultValue="false"
android:key="nested_screen_1_1"
android:title="Nested screen 1.1 check box" />
<CheckBoxPreference
android:defaultValue="true"
android:key="nested_screen_1_2"
android:title="Nested screen 1.2 check box" />
</PreferenceScreen>
nested_screen2_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Nested screen #2">
<CheckBoxPreference
android:defaultValue="true"
android:key="nested_screen2"
android:title="Nested screen 2 check box" />
</PreferenceScreen>
SettingsActivity.java
public class SettingsActivity extends ActionBarActivity implements MyPreferenceFragment.Callback {
private static final String TAG_NESTED = "TAG_NESTED";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.contentSettings, new MyPreferenceFragment())
.commit();
}
}
#Override
public void onBackPressed() {
// this if statement is necessary to navigate through nested and main fragments
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}
#Override
public void onNestedPreferenceSelected(int key) {
getFragmentManager().beginTransaction().replace(R.id.contentSettings, NestedPreferenceFragment.newInstance(key), TAG_NESTED).addToBackStack(TAG_NESTED).commit();
}
}
MyPreferenceFragment.java
// The main preference fragment class
public class MyPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener {
private Callback mCallback;
private static final String KEY_1 = "NESTED_KEY1";
private static final String KEY_2 = "NESTED_KEY2";
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Callback) {
mCallback = (Callback) activity;
} else {
throw new IllegalStateException("Owner must implement Callback interface");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.main_preferences);
// add listeners for non-default actions
Preference preference = findPreference(KEY_1);
preference.setOnPreferenceClickListener(this);
preference = findPreference(KEY_2);
preference.setOnPreferenceClickListener(this);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// here you should use the same keys as you used in the xml-file
if (preference.getKey().equals(KEY_1)) {
mCallback.onNestedPreferenceSelected(NestedPreferenceFragment.NESTED_SCREEN_1_KEY);
}
if (preference.getKey().equals(KEY_2)) {
mCallback.onNestedPreferenceSelected(NestedPreferenceFragment.NESTED_SCREEN_2_KEY);
}
return false;
}
public interface Callback {
public void onNestedPreferenceSelected(int key);
}
}
NestedPreferencesFragment.java
public class NestedPreferenceFragment extends PreferenceFragment {
public static final int NESTED_SCREEN_1_KEY = 1;
public static final int NESTED_SCREEN_2_KEY = 2;
private static final String TAG_KEY = "NESTED_KEY";
public static NestedPreferenceFragment newInstance(int key) {
NestedPreferenceFragment fragment = new NestedPreferenceFragment();
// supply arguments to bundle.
Bundle args = new Bundle();
args.putInt(TAG_KEY, key);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPreferenceResource();
}
private void checkPreferenceResource() {
int key = getArguments().getInt(TAG_KEY);
// Load the preferences from an XML resource
switch (key) {
case NESTED_SCREEN_1_KEY:
addPreferencesFromResource(R.xml.nested_screen1_preferences);
break;
case NESTED_SCREEN_2_KEY:
addPreferencesFromResource(R.xml.nested_screen2_preferences);
break;
default:
break;
}
}
}
Here comes my solution, which is inspired by the original answer but not that complicated. Maybe it'll help someone...
layout/settings.xml:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
layout="#layout/toolbar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content"
android:layout_below="#+id/toolbar"/>
</RelativeLayout>
Classes:
public class SettingsActivity extends ActionBarActivity {
#Override
protected void onCreate( Bundle savedInstanceState ) {
setContentView( R.layout.settings );
super.onCreate( savedInstanceState );
initializeSupportActionBar();
getFragmentManager().beginTransaction().replace( R.id.content, new MainFragment() ).commit();
}
#Override
public void onBackPressed() {
if( !getFragmentManager().popBackStackImmediate() ) super.onBackPressed();
}
}
public class MainFragment extends PreferenceFragment {
public MainFragment() {}
#Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
addPreferencesFromResource( R.xml.pref_main );
// "nested" is the <Preference android:key="nested" android:persistent="false"/>`
findPreference( "nested" ).setOnPreferenceClickListener( new OnPreferenceClickListener() {
#Override public boolean onPreferenceClick( Preference preference ) {
getFragmentManager().beginTransaction().replace( R.id.content, new NestedFragment() ).addToBackStack( NestedFragment.class.getSimpleName() ).commit();
return true;
}
} );
}
public class NestedFragment extends PreferenceFragment {
...
}
I tested it on 4.3 and 5.0.2 and no limitation on nesting levels applies
In my solution you only need one AppCompatActivity and one PreferenceFragement, but several XML files, each having only one level of PreferenceScreens.
XML file list
top level PreferenceScreen
second level PreferenceScreen 0
second level PreferenceScreen 1
second level PreferenceScreen 2
...
This code is for one sub-level (for simplicity and to get the idea), but you can easily extend it to have arbitrary sub-levels of PreferenceScreens.
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment
{
private int xmlId;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
xmlId = R.xml.preferences;
addPreferencesFromResource(xmlId);
}
public void changePrefScreen(int xmlId, int titleId)
{
this.xmlId = xmlId;
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getActivity().getResources().getString(titleId));
getPreferenceScreen().removeAll();
addPreferencesFromResource(xmlId);
}
// will be called by SettingsActivity (Host Activity)
public void onUpButton()
{
if(xmlId == R.xml.preferences) // in top-level
{
// Switch to MainActivity
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
else // in sub-level
{
changePrefScreen(R.xml.preferences, R.string.settings);
}
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)
{
String key = preference.getKey();
//
// Top level PreferenceScreen
//
if(key.equals("top_key_0"))
{
changePrefScreen(R.xml.download_preference_screen, R.string.download_database); // descend into second level
}
// ...
//
// Second level PreferenceScreens
//
if (key.equals("second_level_key_0"))
{
// do something...
}
// ...
}
SettingsActivity.java
public class SettingsActivity extends AppCompatActivity
{
SettingsFragment settingsFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
settingsFragment = new SettingsFragment();
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, settingsFragment)
.commit();
}
//
// Handle what happens on up button
//
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
settingsFragment.onUpButton();
return true;
}
return true;
}
// ...
}
Technically it should work for all Android versions for which the PreferenceFragment is available.
As the issue comes from the part that you are still in the same activity/fragment and the nested pref screen is just a dialog you can do the following:
You can set preference click listener
Get the root view from the dialog:
(PreferenceScreen)preference).getDialog().getWindow()
.getDecorView().getRootView());
Recursively search until find a stub view (there is one, unfortunately I do not know the android.R.id.xxxxx) and set what layout you need as title which will look like the toolbar(You can inflate toolbar):
private Toolbar toolbar;
public void findViewStub(ViewGroup viewGroup) {
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View childView = viewGroup.getChildAt(i);
if( childView instanceof ViewStub){
((ViewStub)childView).setLayoutResource(R.layout.your_title_layout);
toolbar = ((ViewStub)childView).inflate();
}
if (childView instanceof ViewGroup) {
findViewStub((ViewGroup) childView);
}
}
}
toolbar.setNavigationIcon();
toolbar.setNavigationOnClickListener();
toolbar.setTitle();
In the layout you can put only a toolbar. And set the back icon. Register for click on it and having reference to the fragment, on click you can dismiss the dialog. You have set title and etc.

How to instantiate layout for custom preference, using android:layout attribute

I can set appropriate layout for preference through android:layout attribute. For an example
<Preference
android:key="friction"
android:title="#string/friction"
android:layout="#layout/friction_fragment"
android:shouldDisableView="true"
android:defaultValue="30"
android:enabled="true"
android:selectable="true"
android:summary="Bite friction">
</Preference>
where layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:text="#string/friction" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></TextView>
<SeekBar android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="#+id/sbFriction"></SeekBar>
<TextView android:text="#string/friction_little" android:id="#+id/txtSummary" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="Button" android:id="#+id/btnFriction" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
I can get views in OnCreate in PreferenceActivity
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
but these events listeners, that I have set, are not fired.
How I can catch these events, for example - click from button.
Edit.
No, It did not fire any exception.
Here is more detailed code
public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener, OnSeekBarChangeListener
{
private TextView m_txtSummary;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference difficulty = (ListPreference)this.findPreference("difficulty");
difficulty.setSummary(difficulty.getEntry());
difficulty.setOnPreferenceChangeListener(this);
Preference fric = (Preference)this.findPreference("friction");
View v = fric.getView(null, null);
SeekBar sbFriction = (SeekBar)v.findViewById(R.id.sbFriction);
sbFriction.setOnSeekBarChangeListener(this);
Button btnFric = (Button) v.findViewById(R.id.btnFriction);
btnFric.setOnClickListener(m_onClick);
m_txtSummary = (TextView)v.findViewById(R.id.txtSummary);
fric.setSummary(fric.toString());
fric.setOnPreferenceChangeListener(this);
CheckBoxPreference music = (CheckBoxPreference)this.findPreference("music");
music.setOnPreferenceChangeListener(this);
}
private OnClickListener m_onClick = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.getId();
}
};
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue instanceof Boolean)
return true;
preference.setSummary(newValue.toString());
return true;
}
#Override
public void onProgressChanged(SeekBar v, int nProgress, boolean arg2) {
// TODO Auto-generated method stub
m_txtSummary.append(" " + nProgress);
m_txtSummary.invalidate();
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
//notifyChanged();
}
}
I'm not sure you are able to use a custom layout in conjunction with a PreferenceActivity in the way that you describe above.
I believe you should either:
Use a PreferenceScreen via addPreferencesFromResource() and implement classes like CheckBoxPreference, DialogPreference, and MultiSelectListPreference for the SharedPreferences items. (example)
or
Create a custom Activity (not PreferenceActivity) with custom layout (using setContentView()), and manually hook into the SharedPreferences using PreferenceManager.getDefaultSharedPreferences() editing them in the event listeners (View.onClickListener(), etc) using SharedPreferences.Editor .
Hope that makes sense.
Actually I found for an another solution. You could still use the Preferenceability:
Simply add a Fragment which calls the Custom Layout and add it’s class.
However you'll get a warning in the Manifest: (which you can ignore or fix)
[res] (AndroidManifest.xml)
android:name=".SettingsActivity_CUSTOMLAYOUT1"
"YOURPACKAGE.SettingsActivity_CUSTOMLAYOUT1 is not public"
It's only called from your SettingsActivity so you can ignore it
or
if you want to call this Activity from outside just create an own class for it and name it SettingsActivity_CUSTOMLAYOUT1.java.
CODE:
[java] (SettingsActivity.java)
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();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#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)
|| YOURFRAGMENT1.class.getName().equals(fragmentName)
|| YOURFRAGMENT2.class.getName().equals(fragmentName)
|| CUSTOMLAYOUT1.class.getName().equals(fragmentName)
//... Add Fragments
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class YOURFRAGMENT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.YOURFRAGMENTXML1);
setHasOptionsMenu(true);
}
#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 YOURFRAGMENT2 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_private_data);
setHasOptionsMenu(true);
}
#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 FRAGMENTFORCUSTOMLAYOUT1 extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(getActivity(), SettingsActivity.class));
startActivity(new Intent(getActivity(), CUSTOMLAYOUT1.class));
setHasOptionsMenu(true);
}
#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);
}
}
}
class SettingsActivity_CUSTOMLAYOUT1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CUSTOMLAYOUT1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
[xml] (pref_headers.xml)
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$YOURFRAGMENT2"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
<header
android:fragment="YOURPACKAGE.SettingsActivity$CUSTOMLAYOUT1"
android:icon="#drawable/YOURICON"
android:title="#string/TITLE"
android:summary="#string/SUBTITLE"/>
</preference-headers>
[layout] (CUSTOMLAYOUT1.xml)
<?xml version="1.0" encoding="utf-8"?>
<...your custom layout>
Dont forget to add in Manifest.
[res] (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest>
<application
//Add activity
<activity
android:name=".SettingsActivity_CUSTOMLAYOUT1"
android:parentActivityName=".SettingsActivity">
</activity>
</application>
</manifest>

Categories

Resources