【问题标题】:Show Action Bar icons using FragmentActivity implements ActionBar.TabListener使用 FragmentActivity 实现 ActionBar.TabListener 显示 Action Bar 图标
【发布时间】:2015-09-23 13:20:04
【问题描述】:

我正在尝试使用 FragmentActivity(通过实现 ActionBar.TabListener)显示操作栏图标。我正在关注这个例子:http://developer.android.com/training/implementing-navigation/lateral.html#tabs (EffectiveNavigation.zip) 但我不知道如何在操作栏上显示“搜索图标”(在我的情况下),因为目前我只能看到点击菜单按钮时的搜索选项。

jpg

我尝试从 FragmentActivity 切换到 ActionBarActivity 但似乎不支持 ActionBar.TabListener。

MainActivity

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
 * three primary sections of the app. 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}.
 */
AppSectionsPagerAdapter mAppSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will display the three primary sections of the app, one at a
 * time.
 */
ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_main);

    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();

    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayShowTitleEnabled(true);

    // Specify that we will be displaying tabs in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager, attaching the adapter and setting up a listener for when the
    // user swipes between sections.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When swiping between different app sections, select the corresponding tab.
            // We can also use ActionBar.Tab#select() to do this if we have a reference to the
            // Tab.
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by the adapter.
        // Also specify this Activity object, which implements the TabListener interface, as the
        // listener for when this tab is selected.
        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) {
    // When the given tab is selected, switch to the corresponding page in the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

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

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
 * sections of the app.
 */

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    } else if(id == R.id.action_search) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0:
                // The first section of the app is the most interesting -- it offers
                // a launchpad into the other demonstrations in this example application.
                return new LaunchpadSectionFragment();

            default:
                // The other sections of the app are dummy placeholders.
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
                fragment.setArguments(args);
                return fragment;
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return "Section " + (position + 1);
    }
}

/**
 * A fragment that launches other parts of the demo application.
 */
public static class LaunchpadSectionFragment extends Fragment {

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

        // Demonstration of a collection-browsing activity.
        rootView.findViewById(R.id.demo_collection_button)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
                        startActivity(intent);
                    }
                });

        // Demonstration of navigating to external activities.
        rootView.findViewById(R.id.demo_external_activity)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Create an intent that asks the user to pick a photo, but using
                        // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
                        // the application from the device home screen does not return
                        // to the external activity.
                        Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
                        externalActivityIntent.setType("image/*");
                        externalActivityIntent.addFlags(
                                Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        startActivity(externalActivityIntent);
                    }
                });

        return rootView;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public static class DummySectionFragment extends Fragment {

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}
}

menu_main.xml

<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=".MainActivity">
<!-- Search, should appear as action button -->
<item android:id="@+id/action_search"
    android:icon="@drawable/search_icon"
    android:title="@string/action_search"
    app:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_settings"
    android:title="@string/action_settings"
    android:orderInCategory="100"
    app:showAsAction="never" />
</menu>

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.effectivenavigation" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light.DarkActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".CollectionDemoActivity"
        android:label="CollectionDemo"
        android:theme="@android:style/Theme.Holo.Light.DarkActionBar">
    </activity>
</application>

</manifest>

【问题讨论】:

  • 你试过AppCompatActivity吗?
  • @ColinGillespie 是的,当我尝试启动时应用程序崩溃

标签: android android-fragments android-actionbar


【解决方案1】:

尝试将搜索图标的app:showAsAction="ifRoom" 更改为android:showAsAction="always"。仅当您使用 v7 支持库时才需要使用自定义命名空间,但似乎并非如此。考虑到这一点,您还应该更改其他菜单项的命名空间。

【讨论】:

  • 我为他们的问题提供了一个潜在的解决方案。我既不批评也不要求他们澄清。
  • @NasaGeek 刚刚看到您编辑的帖子,您对自定义命名空间到底是什么意思?抱歉,我是 Android 开发新手。
  • 老实说,我自己对它并不十分熟悉。不过,它本质上归结为某些 xml 属性的实现位置。您对系统属性使用 android 命名空间,并为库(如官方支持库)提供的自定义属性使用不同的命名空间。在这里,您使用的是 app 命名空间,尽管您可以给它一个不同的名称。您应该从菜单 xml 中删除 xmlns:app 并将任何 app: 更改为 android:
  • 如果您最终使用 support-v7 来处理您的 ActionBar,那么您需要将命名空间从 android 更改回 showAsAction 属性的自定义命名空间。跨度>
  • @NasaGeek 我正在使用支持库来使用 FragmentActivity,所以如果我将“app”更改为“android”,则会出现错误。如果您查看link (EffectiveNavigation.zip),您可以更好地了解如何制作此示例应用程序。此外,在 styles.xml 中,基本应用程序主题是 android:style/Theme.Holo.Light.DarkActionBar
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
相关资源
最近更新 更多