我正在尝试将数据存储在ClickableSpan中,就像可以使用setTag()和其他类型的元素来完成数据一样。

我已经在stackoverflow中阅读了以下答案:
SpannableString - setTag

它清楚地说:
-创建自己的ClickableSpan子类,其中包含所需的数据,并将其应用于SpannableString。
-创建ClickableSpan并通过数据成员将单词附加到它时,您将可以在onClick()中访问该数据

但是我有点新手,无法弄清楚如何编写代码。

我正在使用扩展ClickableSpan的类来创建我的可点击范围:

// CLASS BEING IMPORTED
public abstract class TouchableSpan extends ClickableSpan {

    // IMPLEMENT SET TAG FUNCTION HERE??

}

// CODE ON ACTIVITY
TouchableSpan touchableSpan = new TouchableSpan() {

    @Override
    public void onClick(View widget) {
        this.setPressed(true);

        // GET TAG INFO HERE. BUT HOW?
    }

    // SET TAG HERE? BUT HOW?

    private boolean mIsPressed;

    public void setPressed(boolean isSelected) {
        mIsPressed = isSelected;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setColor(Color.BLACK);
        ds.bgColor = mIsPressed ? selectedHlColor : 0xffeeeeee;
        ds.setUnderlineText(false);
    }
}

spannablesstringbuilder.setSpan(touchableSpan, index+2, index2, 0);


评论:我知道我应该在所链接问题的评论部分进行澄清,但我没有足够的声誉。

最佳答案

我认为解决方案是在自定义类中使用自定义函数,这样可能有效

// CLASS BEING IMPORTED
public abstract class TouchableSpan extends ClickableSpan {

  // IMPLEMENT SET TAG FUNCTION HERE??

  //COMMENT: YES, LIKE THIS: CAN BE ANY FUNCTION U LIKE

  private String myCustomVar;

  public String getMyVar(){
  return this.myCustomVar;
  }

  public void setMyVar(String myVari){
  this.myCustomVar = myVari;
  return;
  }

}

// CODE ON ACTIVITY
TouchableSpan touchableSpan = new TouchableSpan() {

  @Override
  public void onClick(View widget) {
      this.setPressed(true);

      // GET TAG INFO HERE. BUT HOW?

      //COMMENT: LIKE THIS:

      String extravar = touchableSpan.getMyVar();
      Log.d("TEST", extravar);
  }

  // SET TAG HERE? BUT HOW?

  COMMENT: NOT HERE. SEE BELOW

  private boolean mIsPressed;

  public void setPressed(boolean isSelected) {
      mIsPressed = isSelected;
  }

  @Override
  public void updateDrawState(TextPaint ds) {
      super.updateDrawState(ds);
      ds.setColor(Color.BLACK);
      ds.bgColor = mIsPressed ? selectedHlColor : 0xffeeeeee;
      ds.setUnderlineText(false);
  }
}

//COMMENT: SET YOUR VARIABLE/TAG HERE:

touchableSpan.setMyVar("HOLALA");

spannablesstringbuilder.setSpan(touchableSpan, index+2, index2, 0);

09-28 06:25