@Alexqwerty

Как по нажатию энтер переходить на следующую страницу ViewPager?

public class QuestionTabFragment
    extends ViewPagerFragment<IQuestionTabContract.IPresenter, QuestionPagerAdapter, Question>
    implements IQuestionTabContract.IView, OnAnswerListener {

  public static final String TAG = "FilterFragment";

  @NonNull ViewPager mViewPager;
  @NonNull SmartTabLayout mTablLayout;
  QuestionPagerAdapter mAdapter;
  private ImageView ivLeft;
  private ImageView ivRight;
  private TextView tvCounter;

  public static QuestionTabFragment newInstance() {
    QuestionTabFragment fragment = new QuestionTabFragment();
    Bundle args = new Bundle();
    args.putInt(BaseFragment.ARGUMENT_LAYOUT_ID, R.layout.fragment_question_pager);
    fragment.setArguments(args);
    return fragment;
  }

  private void saveAnswer() {
    if (!isNull(mAdapter) && !isNull(mViewPager)) {
      BaseQuestionFragment fragment =
          ((BaseQuestionFragment) mAdapter.getItem(mViewPager.getCurrentItem()));
      if (!isNull(fragment)) {
        fragment.saveAnswer();
      }
    }
  }

  private void showAnswered(int answerCode, int position) {
    int color;
    if (answerCode == 0) return;
    if (answerCode == 1) {
      color = getResources().getColor(R.color.ciAnswered);
    } else {
      color = getResources().getColor(R.color.ciUnAnswered);
    }
    mTablLayout.getTabAt(position).getBackground().setColorFilter(color, PorterDuff.Mode.SRC);
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    if (view != null) {
      mViewPager = checkNotNull(view.findViewById(R.id.view_pager));
      mTablLayout = checkNotNull(view.findViewById(R.id.tab_layout));
      ivLeft = checkNotNull(view.findViewById(R.id.ivLeft));
      ivRight = checkNotNull(view.findViewById(R.id.ivRight));
      tvCounter = checkNotNull(view.findViewById(R.id.tvCounter));
    }
    //ivLeft.setOnClickListener(v -> {
    //  int position = mViewPager.getCurrentItem();
    //  int newPosition = position - 1;
    //  if (newPosition != -1) mViewPager.setCurrentItem(newPosition, true);
    //});
    //ivRight.setOnClickListener(v -> {
    //  int position = mViewPager.getCurrentItem();
    //  int newPosition = position + 1;
    //  if (newPosition != mViewPager.getChildCount()) mViewPager.setCurrentItem(newPosition, true);
    //});
    tvCounter.setText("0 / 0");
    return view;
  }

  @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mSwipeRefreshLayout.setEnabled(false);

    FabSpeedDial fabSpeedDial = getFabSpeedDial();
    if (fabSpeedDial != null) {
      fabSpeedDial.getMainFab().setImageResource(R.drawable.fab_done);
      fabSpeedDial.getMainFab().setOnClickListener(v -> finish());
    }
  }

  @Override public void onToolbarTitleSet(int titleId) {
    super.onToolbarTitleSet(R.string.title_questions);
  }

  @Override public void showItems(List<Question> items) {
    super.showItems(items);
    mAdapter = new QuestionPagerAdapter(this.getChildFragmentManager());
    for (Question question : items) {
      BaseQuestionFragment fragment = getFragmentFor(question);
      // TODO: 11.05.17 Uncomment line after parcelable implementing
      //            fragment.getArguments().putParcelable("question", question);
      mAdapter.addFragment(fragment, question);
    }
    mViewPager.setAdapter(mAdapter);
    //        mTabLayout.setupWithViewPager(mViewPager);
    mTablLayout.setViewPager(mViewPager);
    if (mViewPager.getChildCount() != 0) {
      mTablLayout.getTabAt(0)
          .getBackground()
          .setColorFilter(getResources().getColor(R.color.ciCurrent), PorterDuff.Mode.SRC);
    }

    //mTabLayout.setCustomTabColorizer(new SmartTabLayout.TabColorizer() {
    //  @Override public int getIndicatorColor(int position) {
    //    return (position % 2 == 0) ? Color.GREEN : Color.RED;
    //  }
    //
    //  @Override public int getDividerColor(int position) {
    //    return (position % 2 == 0) ? Color.BLUE : Color.YELLOW;
    //  }
    //});
    //        ViewUtil.TabLayoutUtils.enableTabs(mTabLayout, false);
    mViewPager.setOffscreenPageLimit(Constants.Wrapper.MAX_NUMBER_QUESTIONS);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      private int lastPosition = 0;

      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
      }

      @Override public void onPageSelected(int position) {
        int currentItem = mViewPager.getCurrentItem();
        //mAdapter.getItem(currentItem).onResume();
        ((BaseQuestionFragment) mAdapter.getItem(currentItem)).refresh();

        //Цвета индикатора
        BaseQuestionFragment fragment = ((BaseQuestionFragment) mAdapter.getItem(lastPosition));
        if (!isNull(fragment)) showAnswered(fragment.getAnswerCode(), lastPosition);
        mTablLayout.getTabAt(position)
            .getBackground()
            .setColorFilter(getResources().getColor(R.color.ciCurrent), PorterDuff.Mode.SRC);
        lastPosition = position;
        tvCounter.setText(
            String.format("%d / %d", mViewPager.getCurrentItem() + 1, mAdapter.getCount()));
      }

      @Override public void onPageScrollStateChanged(int state) {
        ((BaseQuestionFragment) mAdapter.getItem(mViewPager.getCurrentItem())).refresh();
        if (state == ViewPager.SCROLL_STATE_DRAGGING) saveAnswer();
      }
    });
    tvCounter.setText("1 / " + mAdapter.getCount());
  }

  private BaseQuestionFragment getFragmentFor(Question question) {
    BaseQuestionFragment fragment = null;

    switch (question.getType()) {
      case checklist:
        fragment = ChecklistFragment.newInstance(getApplicationContext(), question,
            mPresenter.getBypassId());
        break;
      case radio:
        fragment =
            RadioFragment.newInstance(getApplicationContext(), question, mPresenter.getBypassId());
        break;
      case rating:
        fragment =
            RatingFragment.newInstance(getApplicationContext(), question, mPresenter.getBypassId());
        break;
      case select:
        fragment =
            SelectFragment.newInstance(getApplicationContext(), question, mPresenter.getBypassId());
        break;
      case string:
        fragment =
            StringFragment.newInstance(getApplicationContext(), question, mPresenter.getBypassId());
        break;
      default:
        //                fragment = EmptyFragment.newInstance();
        Timber.e("Unknown question type!");
    }
    fragment.setOnAnswerListener(this);
    return fragment;
  }

  @Override public void showNoItems() {
    showNoItemViews(getResources().getString(R.string.no_question_all),
        R.drawable.ic_assignment_turned_in_24dp, false);
  }

  @Override public void showSuccessfullySavedMessage() {
    showMessage(getString(R.string.successfully_saved_bypass_message));
  }

  @Override public void showItem(@Nullable Question item) {

  }

  @Override public void showEditItem(String itemId) {

  }

  @Override public void showMissingItem() {

  }

  @Override public void setAddress(@Nullable String address) {

  }

  @Override public void setAddress(@StringRes int id) {

  }

  @Override public void onAnswer(@NonNull BaseQuestionFragment fragment) {
    if (isNull(fragment)) return;

    int position = mViewPager.getCurrentItem();
    if (position < mViewPager.getAdapter().getCount() - 1) {
      fragment.saveAnswer();
      //((BaseQuestionFragment) mAdapter.getItem(position)).saveAnswer();
      mViewPager.setCurrentItem(position + 1, true);
    } else {
      getActivity().finish();
    }
  }

  @Override public void onPause() {
    super.onPause();
    saveAnswer();
  }

  @Override public void showItemsToAttach() {
    msgNotImplemented();
  }

  @Override public <C extends CardViewActivity> void showChildItems(Class<C> cls, String parentId) {
    Intent intent = new Intent(getApplicationContext(), cls);
    intent.putExtra(CardViewActivity.EXTRA_ID, parentId);
    startActivity(intent);
  }

  @Override public void showContextMenuFor(@NonNull Question item) {

  }

  @Override public void showChildItems(String parentId) {
    msgNotImplemented();
  }
}
  • Вопрос задан
  • 106 просмотров
Решения вопроса 1
D_mitry
@D_mitry
iOS / Android developer
Не вижу в этой простыне поле для ввода, но если речь о клавиатуре, то можно повесить обработчик кнопки action (done / enter) для EditText
editText.setOnEditorActionListener(new OnEditorActionListener() {        

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_DONE) { 
           //todo
        }
        return false;
    }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы