隐藏链接时如何设置TextView的一部分可点击?

时间:2018-03-23 19:05:52

标签: java android textview spannable

我有一个TextView来显示电子邮件的收件人,原始字符串将类似于"FirstName LastName <xx@yy.com>, FirstName LastName <xx@yy.com>, FirstName LastName <xx@yy.com>"。我希望显示类似"FirstName LastName, FirstName LastName, FirstName LastName"的字符串,而FirstName LastName是可点击的。我知道如何获取FirstName LastName并知道如何使用xx@yy.com点击URLSpan,但它只会使xx@yy.com可点击,我想要做的只是显示FirstName LastName并使其可点击,任何想法?

2 个答案:

答案 0 :(得分:0)

我通过扩展ClickableSpan并传递隐藏信息找到了解决方案,如下面的代码。

public class RecipientsSpan extends ClickableSpan {
    public String name;
    private String emailAddress;
    private int textColor;

    private RecipientsClickHandler recipientsClickHandler;

    public RecipientsSpan(String name, String emailAddress, int textColor) {
        super();
        this.name = name;
        this.emailAddress = emailAddress;
        this.textColor = textColor;
    }

    /**
     * Set the interface that will be used to handle the click event.
     * @param recipientsClickHandler interface to pass in.
     */
    public void setRecipientsClickHandler(@NonNull RecipientsClickHandler recipientsClickHandler) {
        this.recipientsClickHandler = recipientsClickHandler;
    }

    /**
     * Interface to handle click event for different spans inside the same TextView.
     */
    public interface RecipientsClickHandler {
        void onRecipientsClicked(@NonNull String name, @NonNull String emailAddress);
    }

    @Override
    public void onClick(View view) {
        if (recipientsClickHandler != null) {
            recipientsClickHandler.onRecipientsClicked(name, emailAddress);
        }
    }

    /**
     * Make text show the color specified and also avoid the default underline.
     * @param ds TextPaint that will be applied to the text.
     */
    @Override
    public void updateDrawState(@NonNull TextPaint ds) {
        ds.setColor(textColor);
        ds.setUnderlineText(false);
    }
}

答案 1 :(得分:-1)

对于每个TextView,您可以在Java代码中设置onClick侦听器。 因此,您可以轻松地将TextView与mailadress链接