2015-05-09 2 views
10

Я хочу добавить ToolBar в PreferenceActivity в мое приложение для Android. Я написал следующий код.Как добавить ToolBar в PreferenceActivity?

public class SettingsActivity extends PreferenceActivity { 
SendSMS sms; 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.settings); 
    LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent(); 
    android.support.v7.widget.Toolbar bar = (android.support.v7.widget.Toolbar) LayoutInflater.from(this).inflate(R.layout.action_bar_setting, root, false); 
    root.addView(bar, 0); 
    bar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      onBackPressed(); 
     } 
    }); 

}

Это прекрасно работал в моем андроида Kitkat телефона API 19, но сила замкнута в уровне API 10, т.е. пряники. Пожалуйста, предложите мне.

ответ

28

Вам нужен макет, содержащий Toolbar и ListView с android:id="@android:id/list"

activity_settings.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@id/content_frame" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <android.support.v7.widget.Toolbar 
     android:id="@id/toolbar" 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:minHeight="?attr/actionBarSize" 
     android:background="?attr/colorPrimary" /> 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

SettingsActivity.java

public class SettingsActivity extends PreferenceActivity { 

    private AppCompatDelegate mDelegate; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     getDelegate().installViewFactory(); 
     getDelegate().onCreate(savedInstanceState); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_settings); 
     setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); 
     addPreferencesFromResource(R.xml.preferences); 
     ... 
    } 

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

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

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

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

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

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

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

Проверьте мои полностью работающий exa mple:

Справка из Android команды: AppCompatPreferenceActivity

+0

Hidro, зачем макет нужен ListView? –

+0

Работайте со мной после добавления ListView в макет, но панель действий была ниже макета. –

+2

'PreferenceActivity' требует, чтобы в макете' ListView' содержался 'android: id/list', если вы переопределяете макет, поэтому. – hidro

7

Try:

public class SettingsActivity extends AppCompatPreferenceActivity { 
..... 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setupActionBar(); 
    /* getFragmentManager().beginTransaction() 
      .replace(android.R.id.content, new GeneralPreferenceFragment()) 
      .commit(); 
    */ 

    //addPreferencesFromResource(R.xml.pref_general);   
} 

private void setupActionBar() { 
    ViewGroup rootView = (ViewGroup)findViewById(R.id.action_bar_root); //id from appcompat 

    if (rootView != null) { 
     View view = getLayoutInflater().inflate(R.layout.app_bar_layout, rootView, false); 
     rootView.addView(view, 0); 

     Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
    } 

    ActionBar actionBar = getSupportActionBar(); 
    if (actionBar != null) { 
     // Show the Up button in the action bar. 
     actionBar.setDisplayHomeAsUpEnabled(true); 
    } 
} 

app_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.AppBarLayout 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    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> 
+0

Что такое AppCompatPreferenceActivity? –

+0

@Eslam, это класс, который расширяет преференциальную активность. «Новый» -> «Активность настроек» заставит его отобразиться. –

0

XML

<PreferenceScreen xmlns:android ="http://schemas.android.com/apk/res/android"> 
<PreferenceCategory android:title = "@string/pref_cat_theme_title"> 
    <SwitchPreference 
     android:defaultValue = "false" 
     android:key = "@string/pref_key_theme_dark" 
     android:summary = "@string/text_disabled" 
     android:title = "@string/pref_key_theme_title" /> 
    <ListPreference 
     android:defaultValue = "@string/pref_key_text_style_default" 
     android:dialogTitle = "@string/pref_key_text_style_title" 
     android:entries = "@array/pref_key_text_style_options" 
     android:entryValues = "@array/pref_key_text_style_options" 
     android:key = "@string/pref_key_text_style" 
     android:summary = "@string/pref_key_text_style_default" 
     android:title = "@string/pref_key_text_style_title" /> 
    <ListPreference 
     android:defaultValue = "@string/pref_key_text_size_default" 
     android:dialogTitle = "@string/pref_key_text_size_title" 
     android:entries = "@array/pref_key_text_size_options" 
     android:entryValues = "@array/pref_key_text_size_options" 
     android:key = "@string/pref_key_text_size" 
     android:summary = "@string/pref_key_text_size_default" 
     android:title = "@string/pref_key_text_size_title" /> 
</PreferenceCategory> 

<PreferenceCategory android:title = "@string/pref_cat_reminder_title"> 
    <SwitchPreference 
     android:defaultValue = "false" 
     android:enabled = "false" 
     android:key = "@string/pref_key_reminder" 
     android:summary = "@string/text_disabled" 
     android:title = "@string/pref_key_reminder_title" /> 
    <RingtonePreference 
     android:defaultValue = "content://settings/system/notification_sound" 
     android:dependency = "@string/pref_key_reminder" 
     android:key = "@string/pref_key_reminder_tone" 
     android:ringtoneType = "notification" 
     android:summary = "@string/text_disabled" 
     android:title = "@string/pref_key_reminder_tone_title" /> 
    <SwitchPreference 
     android:defaultValue = "false" 
     android:dependency = "@string/pref_key_reminder" 
     android:key = "@string/pref_key_reminder_vibrate" 
     android:summary = "@string/text_disabled" 
     android:title = "@string/pref_key_reminder_vibrate_title" /> 
</PreferenceCategory> 

<PreferenceCategory android:title = "@string/pref_cat_about_title"> 
    <Preference 
     android:key = "@string/pref_key_changelog" 
     android:summary = "@string/pref_key_changelog_summary" 
     android:title = "@string/pref_header_change_log"> 
     <intent 
      android:action = "android.intent.action.VIEW" 
      android:data = "https://play.google.com/store/apps/details?" /> 
    </Preference> 
    <Preference 
     android:key = "@string/pref_key_rate" 
     android:summary = "@string/pref_key_rate_summary" 
     android:title = "@string/pref_key_rate_title"> 
     <intent 
      android:action = "android.intent.action.VIEW" 
      android:data = "https://play.google.com/store/apps/details?" /> 
    </Preference> 
    <Preference 
     android:key = "@string/pref_key_feedback" 
     android:summary = "@string/pref_key_feedback_summary" 
     android:title = "@string/pref_key_feedback_title"> 
     <intent 
      android:action = "android.intent.action.VIEW" 
      android:data = "@string/mail_to_email"> 
      <extra 
       android:name = "android.intent.extra.SUBJECT" 
       android:value = "@string/feedback_email_subject" /> 
     </intent> 
    </Preference> 
    <Preference 
     android:key = "@string/pref_key_more_apps" 
     android:summary = "@string/pref_key_more_apps_summary" 
     android:title = "@string/pref_key_more_apps_title"> 
     <intent 
      android:action = "android.intent.action.VIEW" 
      android:data = "https://play.google.com/store/search?" /> 
    </Preference> 
</PreferenceCategory> 

код Java есть,

 public class ActivitySettings extends PreferenceActivity { 

private static final String TAG = "SB_ActivitySettings"; 
private AppCompatDelegate mDelegate; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    getDelegate().installViewFactory(); 
    getDelegate().onCreate(savedInstanceState); 
    super.onCreate(savedInstanceState); 
    getFragmentManager().beginTransaction().replace(
      android.R.id.content, new ActivitySettings.AboutPreferenceFragment()).commit(); 
} 

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

protected boolean isValidFragment(String fragmentName) { 
    return PreferenceFragment.class.getName().equals(fragmentName) 
      || AboutPreferenceFragment.class.getName().equals(fragmentName); 
} 

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

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

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

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

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

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

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

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

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

@Override 
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); 
} 

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

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

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

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
public static class AboutPreferenceFragment 
     extends PreferenceFragment { 

    private final PreferenceListener mListener = new PreferenceListener(); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     addPreferencesFromResource(R.xml.preferences_list); 

     String keyList[] = getResources().getStringArray(R.array.pref_key_list); 
     Preference preference; 
     String value; 
     for (String pref_key : keyList) { 
      preference = findPreference(pref_key); 
      if (preference != null) { 
       if (preference instanceof ListPreference) { 
        value = ((ListPreference) preference).getValue(); 
       } else if (preference instanceof SwitchPreference) { 
        value = ((SwitchPreference) preference).isChecked() 
          ? "Disabled" : "Enabled"; 
       } else if (preference instanceof RingtonePreference) { 
        value = ((RingtonePreference) preference).getShowSilent() 
          ? "Enabled" : "Silent"; 
       } else { 
        value = ""; 
       } 
       preference.setSummary(value); 
       preference.setOnPreferenceChangeListener(mListener); 
       preference.setOnPreferenceClickListener(mListener); 
      } 
     } 
    } 

    private void showChangeLogDialog() { 
     Utilities.log(TAG, "showChangeLogDialog"); 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 

     WebView webView = new WebView(getActivity()); 
     webView.loadUrl("file:///android_asset/vinoj.html"); 

     builder.setView(webView); 
     builder.setNegativeButton(null, null); 
     builder.setPositiveButton(null, null); 
     builder.show(); 
    } 

    private class PreferenceListener 
      implements Preference.OnPreferenceChangeListener, 
         Preference.OnPreferenceClickListener { 

     @Override public boolean onPreferenceChange(Preference pPreference, Object pObject) { 
      Utilities.log(TAG, "onPreferenceChange: " + pPreference.getKey()); 
      String value; 
      if (pPreference instanceof ListPreference) { 
       value = pObject.toString(); 
      } else if (pPreference instanceof SwitchPreference) { 
       value = ((SwitchPreference) pPreference).isChecked() 
         ? "Disabled" : "Enabled"; 
      } else if (pPreference instanceof RingtonePreference) { 
       value = ((RingtonePreference) pPreference).getShowSilent() 
         ? "Enabled" : "Silent"; 
      } else { 
       value = pObject.toString(); 
      } 
      pPreference.setSummary(value); 
      if (pPreference.getKey().equalsIgnoreCase(
        getString(R.string.pref_key_theme_dark))) { 
       Utilities.restartApplication(getActivity()); 
      } 
      return true; 
     } 

     @Override public boolean onPreferenceClick(Preference pPreference) { 
      String key = pPreference.getKey(); 
      if (key == null) { 
       Utilities.log(TAG, "onPreferenceClick() returning : key = null"); 
       return false; 
      } 
      Utilities.log(TAG, "onPreferenceClick() called key = [" + key + "]"); 
      if (key.equalsIgnoreCase(getString(R.string.pref_key_changelog))) { 
       showChangeLogDialog(); 
      } 
      return true; 
     } 
    } 
} 

}

+1

Хотя этот фрагмент кода может решить вопрос, [включая объяснение] (http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) действительно помогает улучшить качество вашего сообщения. Помните, что вы отвечаете на вопрос читателей в будущем, и эти люди могут не знать причин вашего предложения кода. –

2

Вы можете легко добавить панель инструментов @android:style/Theme.Material.Light.DarkActionBar

В AndroidManifest.xml:

<activity 
    android:name=".activity.SettingsActivity" 
    android:theme="@style/SettingsTheme" 
    android:label="Settings"/> 

В V21/styles.xml

<style name="SettingsTheme" parent="@android:style/Theme.Material.Light.DarkActionBar"> 
<item name="android:colorPrimary">@color/colorPrimary</item> 
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item> 

В V14/стили ,XML для поддержки спины API

<style name="SettingsTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar"> 
<item name="android:actionBarStyle">@style/ActionBar.V14.Movie.NoTitle</item> 

0

Вместо:

public class PreferencesActivity extends Activity 

ли это:

public class PreferencesActivity extends AppCompatActivity 
1

Очень легко и хорошо работает в моем случае, раздувая пользовательскую панель инструментов. В вашем Java коде сделать, как показано ниже,

public class SettingsPrefActivity extends AppCompatPreferenceActivity { 
     // private static final String TAG = SettingsPrefActivity.class.getSimpleName(); 

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

      //setting up toolbar 
      getLayoutInflater().inflate(R.layout.toolbar_setting, (ViewGroup) findViewById(android.R.id.content)); 
      Toolbar toolbar = findViewById(R.id.toolbar); 
      toolbar.setTitle("Settings"); 
      setSupportActionBars(toolbar); 
      getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

      // load settings fragment 
      getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit(); 
     } 

    } 

и в вашем XML-кода на стороне, добавьте одну категорию предпочтения в верхней сделать, как показано ниже,

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 
//put below line at the top of your xml preference layout screen.. 
    <PreferenceCategory android:layout="@layout/toolbar_setting"></PreferenceCategory> 

и в макете папку ресурсов toolbar_setting,

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:local="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="?attr/colorPrimary" 
    android:elevation="@dimen/appbar_elevation" 
    android:minHeight="?attr/actionBarSize" 
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />