以相反的顺序打印arraylist

时间:2017-05-25 10:38:38

标签: java android arrays arraylist textview

我有一个带有按钮的textview,然后我将字符串的ArrayList链接到textview,现在当点击右键查看下一个元素的文本时依此类推。我做到了,但无法从左侧按钮反转过程..!

  • 元素0> "文字0"
  • 元素1> "文字1"
  • 元素2> "文字2"
  • 元素3> "文本3"

默认情况下,文本显示第一个元素"文本0",当我点击右键时显示​​"文本1" ...等等。当它到达最后一个索引时,它会从头开始循环。!

我想要的是在点击左键时显示上一个元素..! 所以如果textview显示"文本2" ,一旦点击左键,"文字1"必须要......等等......当索引为0并单击左键时,它应显示最后一个元素并再次循环..!???

这里是右键的代码,可以在第一个场景中正常使用!

 // inside the onClick ..
 public int viewIndex = 0;

 if (viewIndex == TxtList.size()) {
      viewIndex = 0;
    }
    txt.setText(TxtList.get(viewIndex));
    viewIndex++; 

1 个答案:

答案 0 :(得分:1)

您可以在两个按钮上设置的onclick监听器中执行此操作

leftBtn.setOnClickListener(this);
rightBtn.setOnClickListener(this);
int index = 0;

现在在你的onClick方法中

 @Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.left:
    if(index!=0){
     index--;
     }else { 
        // this else is important because when the index=0, it must show the
       //last element of the array when swiped again..! and begin the cycle over again..!  
      index= TextList.size();
      index--;
    }
    textView.setText(TextList.get(index));
    break;

   case R.id.right:
     index++;
    if(index>=TextList.size()){
    index=0;
    }
 textView.setText(TextList.get(index));
    break;

 }}
相关问题