在按钮上迭代单击侦听器

时间:2016-11-17 13:32:08

标签: java android switch-statement

我有一个ImageView,我已经分配了一个点击监听器。我试图弄清楚如何根据用户在循环中的位置给该侦听器一个新函数。例如,第一次单击将显示TextView,第二次单击将显示另一次,第三次单击将隐藏两者。

public void AddOption(View view) {
        int index = 2;

        switch (index) {
            case 0:
                // if we are using index 0, set the text to index 1 text and change index to 1
                index = 1;
                findViewById(R.id.pollOption3TextInputLayout).setVisibility(View.VISIBLE);
                break;
            case 1:
                index = 2;
                findViewById(R.id.pollOption4TextInputLayout).setVisibility(View.VISIBLE);
                break;
            case 2:
                index = 0;
                findViewById(R.id.pollOption3TextInputLayout).setVisibility(View.GONE);
                findViewById(R.id.pollOption4TextInputLayout).setVisibility(View.GONE);
                break;
        }
    }

我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

将索引保持在方法之外(最简单的方法):

int index = 0;
public void AddOption(View view) {
    switch (index) {
        ...

答案 1 :(得分:1)

创建一个实现View.OnClickListener接口的自定义类。然后向该类添加一个索引整数属性,以及一个用于从其他类更改其值的setter。

公共类CustomClickListener实现了View.OnClickListener {

    private Integer index;

    public CustomClickListener() {
        this.index = 0;
    }

    public void onClick(View v) {
         switch (this.index) {
         case 0:
             //Do wat yo want when index is 0
             break;
         case 1:
            //Do wat yo want when index is 1
             break;
         case 2:
            //Do wat yo want when index is 2
             break;
         }
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

}

然后,在您的自定义单击侦听器类的活动上实例化属性,并将其设置为您的视图。执行此操作后,如果您在任何位置设置此侦听器的索引值,则在单击视图时,索引值将具有正确的值。

public class YourActivityClassWithTheViewAndTheIndex {

    private View yourView;
    private CustomClickListener customClickListener;

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            this.customClickListener = new CustomClickListener()
            this.yourView.setOnClickListener(this.customClickListener);

            //iterate over the index, or whatever, and set it to the listener
            this.customClickListener.setIndex(3);
        }

}

我希望这有帮助!

相关问题