简体   繁体   中英

Change programmatically created textview background on button click

I have created a programmatically TextView in for loop,on textView touch i have set border line on each textview. I want to remove all textView border line on single button click. But it remove only last created textView border Line.

Here is my code

for (int i = 0; i < jsonArray.length(); i++) {
  JSONObject c = jsonArray.getJSONObject(i);
  final String text = c.getString(Constants.CARD_TEXT);
  final AppCompatTextView textView = new AppCompatTextView(Card.this);
  textView.setId(i);
  textView.setText(text);
  textView.setY((int) (hgt * yaxis / 100));
  final int finalI1 = i;
  txtNext.setOnClickListener(new View.OnClickListener() {
    @SuppressLint("ResourceType")
    @Override
    onClick(View v) {
      for (int j = 0; j <= finalI1; j++) {
        Log.e("Clicked1221", String.valueOf(textView.getId() - j));
        if (textView.getId() - j == j) {
          ;
        }
        textView.setBackgroundResource(0);
      }
    }
  }
});

final int finalI = i;
textView.setOnTouchListener(new View.OnTouchListener() {
  @Override
  public boolean onTouch(View v, MotionEvent event) {

    textView.setSelected(true);

    if (gestureDetector.onTouchEvent(event)) {

      if (textView.isSelected()) {
        textView.setBackgroundResource(R.drawable.doted);
      }
      return true;
    }
    imgBackground.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {

        textView.setBackgroundResource(0);

        textView.setSelected(false);

        return false;
      }
    });
    return true;
  }
});

layoutImage.addView(textView);

You are calling textView.setBackgroundResource(R.drawable.doted); on only one text view, if you want to change background of all created textviews, you have to store reference of each created textview somewhere, create a list of textviews, and add each new text view to that list and in onTouchListener do something like this

 for(textView:textViews){
     textView.setBackgroundResource(0);

     textView.setSelected(false);

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM