添加preferenceFragment到FragmentPagerAdapter [英] Adding PreferenceFragment to FragmentPagerAdapter

查看:829
本文介绍了添加preferenceFragment到FragmentPagerAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个 preferenceFragment FragmentPagerAdapter

我的类扩展 FragmentActivity ,我已经试过 FragmentTransaction ,如下图所示,以及尝试添加到容器似乎无法得到任何工作。 没有的错误抛出,其实什么也没发生。

主要活动:

@覆盖 保护无效的onCreate(包savedInstanceState){     super.onCreate(savedInstanceState);     的setContentView(R.layout.activity_main);     mSectionsPagerAdapter =新SectionsPagerAdapter(getSupportFragmentManager());     mViewPager =(ViewPager)findViewById(R.id.pager);     mViewPager.setAdapter(mSectionsPagerAdapter); }

activity_main.xml:

< android.support.v4.view.ViewPager     的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android     的xmlns:工具=htt​​p://schemas.android.com/tool​​s     机器人:ID =@ + ID /寻呼机     机器人:layout_width =match_parent     机器人:layout_height =match_parent     工具:上下文=MainActivity。> < /android.support.v4.view.ViewPager>

我的选项菜单中选择:

android.app.FragmentManager FM; @覆盖 公共布尔onOptionsItemSelected(菜单项项){     开关(item.getItemId()){     案例R.id.menu_settings:         JJSettings设置=新JJSettings();         FM = getFragmentManager();         FragmentTransaction fragTrans = fm.beginTransaction();         //我也试过`替换()`这里。同样的没有反应的结果。         fragTrans.add(设置,设置);         fragTrans.commit();         返回true;     案例R.id.menu_help:         menuHelp();         返回true;     默认:         返回super.onOptionsItemSelected(项目);     } }

我的设置 片段

公共类JJSettings扩展preferenceFragment {     @覆盖     公共无效的onCreate(包savedInstanceState){         super.onCreate(savedInstanceState);         加preferencesFromResource(R.xml.settings);     } }

我的preference会坚持使用片段如果可能的话,这意味着我宁愿不延长 preferenceActivity 或采取用户到另一个活动调用 preferenceFragment ,如果可能的话。我只希望我错过了一些在我的研究工作。


修改

 公共类SectionsPagerAdapter扩展FragmentPagerAdapter {
    私人诠释_count = 2;

    公共SectionsPagerAdapter(FragmentManager FM){超(FM); }

    @覆盖
    公共对象instantiateItem(ViewGroup中的容器,INT位置){
        返回super.instantiateItem(集装箱,位置);
    }

    @覆盖
    公共片段的getItem(INT位置){
        开关(位置){
        情况下0:
            返回新JJMainFragment();
        情况1:
            返回新JJPendingFragment();
        默认:
            返回null;
        }
    }

    公共无效setCount(诠释计数){this._count =计数; }

    @覆盖
    公众诠释getCount将(){返​​回this._count; }

    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        开关(位置){
        情况下0:
            返回的getString(R.string.c_list).toUpperCase(Locale.ENGLISH);
        情况1:
            返回的getString(R.string.c_pending).toUpperCase(Locale.ENGLISH);
        }
        返回null;
    }
}
 

解决方案

<一个href="http://stackoverflow.com/questions/13501424/fragmentpageradapter-exists-only-in-android-support-v4-app-and-not-android-app">This回答促使我使用V13支持库,其中包括使用善意,善意android.app.Fragments所以它可以支持preferenceFragment一个FragmentPagerAdapter的解决方案。

假设你使用Eclipse和运行具有滚动选项卡+刷卡导航(它给你的V4寻呼机样板)新的应用程序向导,这里有您需要升级到V13的修改:

  • 从您的库中删除Android的支持 - v4.jar文件夹
  • 复制从SDK_PATHAndroid的支持 - v13.jar\演员\机器人\ SUPPORT \ V13;如果它不存在,使用SDK管理器安装或更新高级/ Android的支持库

然后,在Java文件:

  • 从V4至V13变化FragmentPagerAdapter进口
  • 更改FragmentActivity一个普通的活动
  • 更改来电getSupportFragmentManager到getFragmentManager
  • 导入所有必需的类android.app而不是android.support.v4
  • (例外情况:你仍然需要使用V4 ViewPager,但它是兼容的)

我已经复制下面的修改后的源,核实最新杰利贝恩。

MainActivity.java:

 包com.example.pagerwith preferencesfragment;

进口java.util.Locale中;

进口android.app.Activity;
进口android.app.Fragment;
进口android.app.FragmentManager;
进口android.os.Bundle;
。进口的Andr​​oid preference preferenceFragment;
进口android.support.v13.app.FragmentPagerAdapter;而不是v4.app // ...
进口android.support.v4.view.ViewPager;
进口android.view.Gravity;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.TextView;

公共类MainActivity延伸活动{//不再FragmentActivity

    //这些评论是现在外的日期; V13,不是V4
    / **
     *在{@link android.support.v4.view.PagerAdapter},将提供
     *对于每个部分的片段。我们使用
     * {@link android.support.v4.app.FragmentPagerAdapter}衍生物,它
     *将让每一个加载的片段记忆。如果这成为过记忆
     *密集,它可能是最好切换到
     * {@link android.support.v4.app.FragmentStatePagerAdapter}。
     * /
    SectionsPagerAdapter mSectionsPagerAdapter;

    / **
     *在{@link ViewPager}将承载部分内容。
     * /
    ViewPager mViewPager;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        //创建将返回一个片段为三个的适配器
        //应用程序的主要部分。
        mSectionsPagerAdapter =新SectionsPagerAdapter(
                getFragmentManager()); //而非getSupportFragmentMangager

        //设置的ViewPager与部分适配器。
        mViewPager =(ViewPager)findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.main,菜单);
        返回true;
    }

    / **
     * A {@link FragmentPagerAdapter}返回对应的片段
     *章节/标签/页之一。
     * /
    公共类SectionsPagerAdapter扩展FragmentPagerAdapter {

        公共SectionsPagerAdapter(FragmentManager FM){
            超(FM);
        }

        @覆盖
        公共片段的getItem(INT位置){
            //这是只是为了显示它编译
            如果(位置== 0){
                //你要真正使这个别的地方公共类..
                返回新的preferenceFragment(){
                    @覆盖
                    公共无效的onCreate(包savedInstanceState){
                        super.onCreate(savedInstanceState);
                        加preferencesFromResource(R.xml.settings_ preferences);
                    }
                };
            }
            //的getItem被称为实例化片段给定的页面。
            //返回一个DummySectionFragment(定义为静态内部类
            下图)与页面数量作为其唯一的参数//。
            片段片段=新DummySectionFragment();
            捆绑的args =新包();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER,位置+ 1);
            fragment.setArguments(参数);
            返回片段;
        }

        @覆盖
        公众诠释getCount将(){
            //显示3总页​​数。
            返回3;
        }

        @覆盖
        公共CharSequence的getPageTitle(INT位置){
            区域设置L = Locale.getDefault();
            开关(位置){
            情况下0:
                返回的getString(R.string.title_section1).toUpperCase(升);
            情况1:
                返回的getString(R.string.title_section2).toUpperCase(升);
            案例2:
                返回的getString(R.string.title_section3).toUpperCase(升);
            }
            返回null;
        }
    }

    / **
     *一个虚拟片段重新presenting应用程序的一部分,但只是
     *显示虚拟文本。
     * /
    公共静态类DummySectionFragment扩展片段{
        / **
         *片段参数重新presenting本章节号
         * 分段。
         * /
        公共静态最后弦乐ARG_SECTION_NUMBER =section_number标;

        公共DummySectionFragment(){
        }

        @覆盖
        公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
                捆绑savedInstanceState){
            查看rootView = inflater.inflate(R.layout.fragment_main_dummy,
                    集装箱,假);
            TextView的dummyTextView =(TextView中)rootView
                    .findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments()调用getInt(
                    ARG_SECTION_NUMBER)));
            返回rootView;
        }
    }

}
 

settings_ preferences.xml:

 &LT; XML版本=1.0编码=UTF-8&GT?;

&LT; preferenceScreen
   的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android&GT;

   &LT; preferenceCategory
      机器人:关键=my_category_key
      机器人:标题=我的标题&GT;

       &LT;复选框preference
         机器人:关键=preF_KEY
         机器人:标题=标题
         机器人:总结=摘要
         安卓:设置defaultValue =假
         /&GT;

   &LT; / preferenceCategory&GT;

&LT; / preferenceScreen&GT;
 

I am trying to add a PreferenceFragment to a FragmentPagerAdapter.

My class extends FragmentActivity, I have tried FragmentTransaction, as shown below as well as trying to add to the container and can't seem to get anything to work. No errors are thrown, in fact nothing happens.

Main Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

activity_main.xml:

<android.support.v4.view.ViewPager 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
</android.support.v4.view.ViewPager>

My Options menu selection:

android.app.FragmentManager fm;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        JJSettings settings = new JJSettings();
        fm = getFragmentManager();
        FragmentTransaction fragTrans = fm.beginTransaction();
        // I also tried `replace()` here as well. Same 'nothing happens' result.
        fragTrans.add(settings, "settings");
        fragTrans.commit();
        return true;
    case R.id.menu_help:
        menuHelp();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

My settings Fragment:

public class JJSettings extends PreferenceFragment {

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

My preference would be to stick with Fragments if possible, meaning I'd rather not extend PreferenceActivity or take the user to another Activity that calls the PreferenceFragment, if at all possible. I'm just hoping I missed something in my research.


Edit

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private int _count = 2;

    public SectionsPagerAdapter(FragmentManager fm) { super(fm); }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return new JJMainFragment();
        case 1:
            return new JJPendingFragment();
        default:
            return null;
        }
    }

    public void setCount(int count) { this._count = count; }

    @Override
    public int getCount() { return this._count; }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
        case 0:
            return getString(R.string.c_list).toUpperCase(Locale.ENGLISH);
        case 1:
            return getString(R.string.c_pending).toUpperCase(Locale.ENGLISH);
        }
        return null;
    }
}

解决方案

This answer led me to the solution of using the v13 support library, which includes a FragmentPagerAdapter that uses bona-fide android.app.Fragments so it can support the PreferenceFragment.

Assuming you use Eclipse and run the new app wizard with the "Scrollable Tabs + Swipe" Navigation (which gives you the v4 pager boilerplate), here are the modifications you need to make to upgrade to v13:

  • Delete "android-support-v4.jar" file from your libs folder
  • Copy "android-support-v13.jar" from SDK_PATH\extras\android\support\v13; if it's not there, use the SDK manager to install or update "Extras/Android Support Library"

Then, in the Java file:

  • Change FragmentPagerAdapter import from v4 to v13
  • Change FragmentActivity to a plain Activity
  • Change calls to getSupportFragmentManager to getFragmentManager
  • Import all necessary classes from android.app instead of android.support.v4
  • (Except: you still need to use the v4 ViewPager, but it's compatible)

I've copied the modified source below, verified on latest Jellybean.

MainActivity.java:

package com.example.pagerwithpreferencesfragment;

import java.util.Locale;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v13.app.FragmentPagerAdapter; // instead of v4.app...
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends Activity { // no longer FragmentActivity

    // these comments are now out-of-date; v13, not v4
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getFragmentManager()); // instead of getSupportFragmentMangager

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // this is just to show it compiles
            if (position == 0) {
                // you should really make this a public class elsewhere..
                return new PreferenceFragment() {
                    @Override
                    public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        addPreferencesFromResource(R.xml.settings_preferences);
                    }
                };
            }
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main_dummy,
                    container, false);
            TextView dummyTextView = (TextView) rootView
                    .findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(
                    ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

}

settings_preferences.xml:

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

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

   <PreferenceCategory
      android:key="my_category_key"
      android:title="My Title">

       <CheckBoxPreference
         android:key="pref_key"
         android:title="Title"
         android:summary="Summary"
         android:defaultValue="false"
         />

   </PreferenceCategory>

</PreferenceScreen>

这篇关于添加preferenceFragment到FragmentPagerAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆