0

Я недавно увлеклась андроид разработкой (меньше месяца), часто беру готовые коды и изменяю для своей программы. Взяла код, который прокручивает текст вперед при клике по кпопке buttonNext, не могу разобраться, как сделать так, чтобы текст прокручивался назад при клике по кнопке buttonPrev. Вот код:

private TextSwitcher mTextSwitcher;
private Integer[] mWordsArray = { R.string.about1, R.string.about2, R.string.about3, R.string.about4, R.string.about5};
int mCurrentIndex;
Button buttonNext;
Button buttonPrev;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_food_learn_words_coffe_);
buttonNext = (Button) findViewById(R.id.buttonNext);
buttonPrev = (Button) findViewById(R.id.buttonPrev);
mTextSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
mTextSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
mTextSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
mTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            TextView textView = new TextView(this);
            textView.setTextSize(20);
            textView.setTextColor(Color.BLACK);
            textView.setGravity(Gravity.CENTER_HORIZONTAL);
            textView.setTypeface(Typeface.DEFAULT);
            return textView;

        }
    });

    mCurrentIndex = 0;
    mTextSwitcher.setText(getResources().getString(mWordsArray[mCurrentIndex]));


}
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.buttonNext:
             if (mCurrentIndex == mWordsArray.length - 1) {
                mCurrentIndex = 0;
                mTextSwitcher.setText(getResources().getString(mWordsArray[mCurrentIndex]));
        } else {
            mTextSwitcher.setText(getResources().getString(mWordsArray[++mCurrentIndex]));
        }
        break;
    case R.id.buttonPrev:
    //здесь нужно описать условие для прокрутки назад
        if (mCurrentIndex == mWordsArray.length - 1) {
            mCurrentIndex = 0;
            mTextSwitcher.setText(getResources().getString(mWordsArray[mCurrentIndex]));
        } else {
            mTextSwitcher.setText(getResources().getString(mWordsArray[--mCurrentIndex]));
        }

        break;
    default:
        break;
    }
}

1 ответ 1

1

Внимательно посмотрите на алгоритм прокрутки вперед. Если текущий элемент - последний, то делаем текщим первый (0ой) и переключаемся на него. Иначе увеличиваем текущий индекс и опять таки переключаемся на него. Далее думаем как этот алгоритм переделать под обратный отсчет. То что Вы поменяли увеличение индекса на уменьшение это правильно, но надо было ещё поменять условие: теперь мы идем не с первого до последнего, а наоборот и след овательно надо поменять

if (mCurrentIndex == mWordsArray.length - 1) {
    mCurrentIndex = 0;

на

if (mCurrentIndex == 0) {
    mCurrentIndex = mWordsArray.length - 1;
1
  • спасибо за подробный ответ! Честно говоря, не поняла вообще смысл этой записи mCurrentIndex == mWordsArray.length - 1, поэтому не смогла исправить как нужно.
    – VolhaGomel
    26 янв 2016 в 20:21

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.