【问题标题】:Adding Array of customized View in android and setting onClickListener mutually exclusive在android中添加自定义View的Array并设置onClickListener互斥
【发布时间】:2017-02-03 06:36:39
【问题描述】:

我正在使用数组添加自定义视图。数组元素通过扩展布局并将这些元素添加到 ViewGroup 来初始化,如图所示。 当我以某种方式设置 onClickListener 以使单击的视图的背景为强调色时,它会发生但为了使其互斥,以便一旦单击视图,其他视图的背景应该像原来一样透明最初我使用了以下代码但是当我单击视图时,我的应用程序停止响应。如果我的方法不正确,请建议我获得所需结果的正确方法。

这应该发生:

这不应该发生:

if(noOfChild>1) {
        for (j = 0; j < noOfChild; j++) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
            childButton[j] = (inflater.inflate(R.layout.child_selection_button, null));
            childButton[j].setId(j);
            children.addView(childButton[j], new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
            childButton[j].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setBackgroundColor(ContextCompat.getColor(MainScreen.this, R.color.dimAccent));
                    //   for (int k =0;k<noOfChild;k++){
                    //       while(k!=v.getId()){
                    //           childButton[k].setBackgroundColor(ContextCompat.getColor(MainScreen.this, R.color.transparent));
                    //       }
                    //   }
                }
            });
        }
    }

【问题讨论】:

    标签: android arrays view onclicklistener


    【解决方案1】:

    您可以保留一个局部变量,该变量显示最后一个选定项目的位置。然后在你的onClick() 方法中切换位置和背景颜色:

    private View lastSelected;
    
    //... rest of code ...
    
    //Inside for loop
    public void onClick(View v){
          if (lastSelected == null){
               lastSelected = v;
               selectItem(lastSelected);
          }
          else
          {
          deselectItem(lastSelected);
          lastSelected = v;
          selectItem(lastSelected);
          }
    }
    
    private void selectItem(View v){
         v.setBackgroundColor(ContextCompat.getColor(MainScreen.this,R.color.dimAcent));
    }
    
    private void deselectItem(View v){
          v.setBackgroundColor(ContextCompat.getColor(MainScreen.this, R.color.transparent));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      相关资源
      最近更新 更多