web-dev-qa-db-ja.com

FragmentTabHost-タグnullで認識されているタブがありません

数日前、TabHostFramgentFragmentとともにNavigationDrawerに実装しましたが、次のエラーという問題に直面しました。

Java.lang.IllegalStateException:タグnullで認識されているタブがありません

NavigationDrawerの最初のアイテムリストがTabHostFragmentであるため、すべてが完全に機能するため、完全に機能しますが、問題は、例として2番目のアイテムに移動してから最初のアイテムに戻りたいので、試行するたびにクラッシュします。

ここSOcode.google.comなど、どこでも検索していましたが、まだ適切な答えが得られません。

私のtab_Host_test_2.xmlは次のようになります:

  <Android.support.v4.app.FragmentTabHost xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:id="@Android:id/tabhost"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent" >

    <LinearLayout
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:orientation="vertical" >

        <TabWidget
            Android:id="@Android:id/tabs"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:orientation="horizontal" />

        <FrameLayout
            Android:id="@Android:id/tabcontent"
            Android:layout_width="0dp"
            Android:layout_height="0dp"
            Android:layout_weight="0" />

        <FrameLayout
            Android:id="@+id/realtabcontent"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            Android:layout_weight="1" />
    </LinearLayout>

</Android.support.v4.app.FragmentTabHost>

NavigationDrawerを取得したactivity_main.xmlは次のようになります:

 <Android.support.v4.widget.DrawerLayout
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/drawer_layout"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        Android:id="@+id/frame_container"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent" />


    <!-- Listview to display slider menu -->
    <ListView
        Android:id="@+id/list_slidermenu"
        Android:layout_width="240dp"
        Android:layout_height="match_parent"
        Android:layout_gravity="start"
        Android:choiceMode="singleChoice"
        Android:divider="@color/list_divider"
        Android:dividerHeight="1dp"
        Android:listSelector="@drawable/list_selector"
        Android:background="@color/list_background"/>
</Android.support.v4.widget.DrawerLayout>

私のTabHostFragment.Java

    public class TabHostFragment extends Fragment {

    public TabHostFragment(){

    }
    private FragmentTabHost mTabHost;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab_Host_test2, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mTabHost = (FragmentTabHost)view.findViewById(Android.R.id.tabhost);
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
                MisOfertasFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
                RecomendacionesFragment.class, null);




    }

}

私のActivityMain.Java

public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    // saber si esta abierto
    public boolean mDrawerOpened;
    // nav drawer title
    private CharSequence mDrawerTitle;
    private FragmentTabHost mTabHost;
    // used to store app title
    private CharSequence mTitle;

    //para ponerlo visible
    public MenuItem mi;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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


        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        //AyudaSugerencias
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));


        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(
                        Html.fromHtml("<font color='ffffff'>"
                                + mTitle + "</font>"));

                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
                mDrawerOpened = false;
                syncState();

            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(
                        Html.fromHtml("<font color='ffffff'>"
                                + mDrawerTitle + "</font>"));

                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
                mDrawerOpened = true;
                syncState();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {


        getMenuInflater().inflate(R.menu.main, menu);


        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Fragment fragment = null;
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            case R.id.ofertasRefresh:
                return true;
            case R.id.menu_search:
                return true;
            case R.id.newOffer:
                getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        if (mDrawerOpened) {
            menu.removeItem(R.id.ofertasRefresh);
            menu.removeItem(R.id.menu_search);
            menu.removeItem(R.id.newOffer);
        }
        if (!mDrawerOpened) {
            menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle);
        }
        return super.onPrepareOptionsMenu(menu);

    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     */
    private void displayView(int position) {
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
        Fragment fragment = null;

        switch (position) {
            case 0:
                fragment = new TabHostFragment();
                break;
            case 1:
                fragment = new RecomendacionesFragment();
                break;
            case 2:
                fragment = new LocalizacionFragment();
                break;
            case 3:
                fragment = new ListaProductosFragment();
                break;
            case 4:
                fragment = new ConfiguracionFragment();
                break;
            case 5:
                fragment = new AyudaSugerenciasFragment();
                break;
            case 6:
                fragment = new AyudaSugerencias();
                break;

            default:

                break;
        }


        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit(); /// here says that replace Android.app.Fragment in FragmentTransaction cannot be applied...

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }


    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);

    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }



}

完全なLogCatエラーは次のとおりです。

  03-04 16:53:05.708    2232-2232/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 2232
Java.lang.IllegalStateException: No tab known for tag null
        at Android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.Java:330)
        at Android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.Java:280)
        at Android.view.View.dispatchAttachedToWindow(View.Java:13406)
        at Android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.Java:2707)
        at Android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.Java:2714)
        at Android.view.ViewGroup.addViewInner(ViewGroup.Java:3919)
        at Android.view.ViewGroup.addView(ViewGroup.Java:3733)
        at Android.view.ViewGroup.addView(ViewGroup.Java:3678)
        at Android.view.ViewGroup.addView(ViewGroup.Java:3654)
        at Android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.Java:958)
        at Android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.Java:1126)
        at Android.support.v4.app.BackStackRecord.run(BackStackRecord.Java:739)
        at Android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.Java:1489)
        at Android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.Java:454)
        at Android.os.Handler.handleCallback(Handler.Java:739)
        at Android.os.Handler.dispatchMessage(Handler.Java:95)
        at Android.os.Looper.loop(Looper.Java:135)
        at Android.app.ActivityThread.main(ActivityThread.Java:5221)
        at Java.lang.reflect.Method.invoke(Native Method)
        at Java.lang.reflect.Method.invoke(Method.Java:372)
        at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:899)
        at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:694)

[〜#〜]編集[〜#〜]

@ YS の答えは、私が求めていたものとは少し異なっていましたが、それは解決策になる可能性がありますが、まったくうまくいきませんでした。NavigationDrawerは下にあります。 TabHostFragmentなど...レイアウトを変更したくありません。

17
Skizo-ozᴉʞS

エラーが示唆するように

Java:不正な状態の例外:タグがnullであることがわかっているタブがありません

tabHostを初期化しようとしましたが、_TabHost was null_。


TabHostの初期化に使用したコードを試してみてください。問題なく動作しますが、コードはonCreateView()に保管してください。この問題は、onViewCreated()FragmentTabHostを設定しようとしたときに発生します。これは遅すぎます。 onCreateView()で設定し、ビューObjectを返す前に少なくとも1つのタブを追加してみてください。

_@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    // Create FragmentTabHost
    mTabHost = new FragmentTabHost(getActivity());
    // Locate fragment1.xml to create FragmentTabHost
    mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment1);
    mTabHost.addTab(mTabHost.newTabSpec("groups").setIndicator("",getResources().getDrawable(R.drawable.tab_group_icon)),FragmentTab1.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("",getResources().getDrawable(R.drawable.tab_user_icon)),FragmentTab2.class, null);

    MainActivity.fabButton.setVisibility(View.VISIBLE);
    return mTabHost;
}
_

Layoutを次のように変更します。

_<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:orientation="vertical" >

    <FrameLayout
        Android:layout_width="match_parent"
        Android:layout_height="0dip"
        Android:layout_weight="1" />

    <Android.support.v4.app.FragmentTabHost
        Android:id="@Android:id/tabhost"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content" >

        <FrameLayout
            Android:id="@Android:id/tabcontent"
            Android:layout_width="0dp"
            Android:layout_height="0dp"
            Android:layout_weight="0" />

    </Android.support.v4.app.FragmentTabHost>

</LinearLayout>
_

それが役に立てば幸い。

12
Maveňツ

ここで使用できるタブを表示する別の方法があります。

TabHostFragmentを次のように定義します。

_public class TabHostFragment extends Fragment implements ActionBar.TabListener{

    public TabHostFragment(){

    }

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    ViewPager mViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab_Host_test2, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getChildFragmentManager());

        final ActionBar actionBar = ((FragmentActivity)getActivity()).getSupportActionBar();

        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mViewPager = (ViewPager) view.findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(
                actionBar.newTab()
                        .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int i) {
            Fragment f = null;
            switch (i) {
                case 0:
                    f = new MisOfertasFragment();
                    break;

                case 1:
                    f = new RecomendacionesFragment();
                    break;
            }

            return f;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return getFragmentTitle(position);
        }

        private String getFragmentTitle(int position){
            if(position == 0)
                return "Tab 1";
            else if(position == 1)
                return "Tab 2";
            else
                return "";
        }
    }
}
_

_tab_Host_test2.xml_を次のように定義します。

_<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" />
_

残りのコードは同じままです。

これを試して。これはうまくいくはずです。

編集:

これをdisplayView()メソッドに追加します。

_if(position != 0)
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
_
2
Y.S

このTabHostFragment(com.my.TabHostFragmentのような完全なパス)を使用している場所を.xmlファイルで指定します。お気に入り

 <com.my.TabHostFragment
        Android:id="@+id/fragmentId"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
         />
0