就我而言,以下片段活动工作正常。
((CommentActivity)getActivity()).pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtComment.getWindowToken(), 0);
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
更新:
这是我的片段活动,其中两个片段(CommentFragment,AnotherFragment)在 ViewPager 中打开
public class CommentActivity extends FragmentActivity {
ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pager = (ViewPager) findViewById(R.id.viewPager);
.......
.......
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return CommentFragment.newInstance();
default: return AnotherFragment.newInstance();
}
}
@Override
public int getCount() {
return 2;
}
}
}
如果在 CommentFragment 中为 EditText 出现键盘并且想要切换到 AnotherFragment 并且想要在切换时隐藏键盘
public class CommentFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
.........
.........
.........
((CommentActivity)getActivity()).pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
final InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtComment.getWindowToken(), 0);
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}