【问题标题】:onOptionsItemSelected hook called for wrong fragmentonOptionsItemSelected 钩子调用了错误的片段
【发布时间】:2014-07-17 15:37:42
【问题描述】:

我有一个简单的活动,FragmentPagerAdapterFragments 中显示一些图表。我可以通过单击ActionBar 中的选项卡或在一侧或另一侧滑动来浏览它们。这就是Fragment 的样子:

public static class ChartFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
    private int section;

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static ChartFragment newInstance(int sectionNumber) {
        ChartFragment fragment = new ChartFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public ChartFragment() {
        // enable menu for fragment
        setHasOptionsMenu(true);
    }

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

        int arg = getArguments().getInt(ARG_SECTION_NUMBER);
        section = arg;
        return generateChart(arg);
    }

    private View generateChart() {
        // generate the chart
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       // handle item selection
       switch (item.getItemId()) {
          case R.id.action_button:
             Log.e(TAG, "Section: " + section);
             return true;
          default:
             return super.onOptionsItemSelected(item);
       }
    }
}

(供您参考:代码示例基于此内置 ADT)

我在ActionBar 中为每个片段启用了菜单,点击在onOptionsItemSelected 钩子中处理。当在ActionBar 中手动选择一个选项卡时,一切正常,但是当浏览片段并在导航到Fragment 后不久单击ActionBar 按钮action_button 时,会显示先前显示的Fragment 的sectionnumber !
刷卡时我该怎么做才能使其行为“正常”?

【问题讨论】:

    标签: java android android-fragments tabs


    【解决方案1】:

    在滑动发生时,最后一个完全显示的片段处理onOptionsItemSelected 钩子。为了避免用户单击错误片段的按钮,我只是在转换时阻止由按钮单击触发的动作。 因此我使用这个监听器:

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 0) {
                    isScrolling = false;
                } 
                else {
                    isScrolling = true;
                }               
            }
    
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
    
            }
    
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }           
    });
    

    第二种方法:

    跟踪所有Fragment 实例并处理活动中的钩子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多