Java OnOptions ItemSelected钩子调用了错误的片段
我有一个简单的活动,Java OnOptions ItemSelected钩子调用了错误的片段,java,android,android-fragments,tabs,Java,Android,Android Fragments,Tabs,我有一个简单的活动,FragmentPagerAdapter在Fragments中显示一些图表。我可以通过单击ActionBar中的选项卡或在一侧或另一侧滑动来浏览它们。这就是片段的样子: public static class ChartFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private int section;
FragmentPagerAdapter
在Fragments
中显示一些图表。我可以通过单击ActionBar
中的选项卡或在一侧或另一侧滑动来浏览它们。这就是片段的样子:
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
中的菜单,点击在onoptionItemSelected
hook中处理。当在ActionBar
中手动选择选项卡时,一切正常,但当浏览片段并在导航到Fragment
后不久单击ActionBar
按钮action\u按钮
时,会显示先前显示的片段的节号
在刷卡时,如何使其“正常”运行?在刷卡时,最后一个完全显示的片段处理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);
}
});
第二种方法:
跟踪所有片段
实例并处理活动中的挂钩