android – 带链接的Textview onclicklistener

前端之家收集整理的这篇文章主要介绍了android – 带链接的Textview onclicklistener前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个带有锚点的html字符串的textview.当我单击textview时我想调用例如一个名为A的方法,当我单击textview中的一个链接时,我想调用一个名为B的方法.我得到了这个工作但是我遇到了一个问题:当我点击一个链接时,方法调用B,但也调用方法A.当我点击链接时,如何确保只调用方法B而不是B和A?

我的代码

for (int i = 0; i < ingevoegd.length(); i++) {
        JSONObject soortingevoegd = ingevoegd.getJSONObject(i);
        String type = soortingevoegd.getString("type");         
        if (type.equals("Vis")) {
            String link = "<a href = 'com.aquariumzoeken.pro://Soortweergave?selected="
                    + naam + "&type=Vis" + "'>" + naam + "</a>";
            text = text.replaceAll(naam,link);
        }
    }

    TextView texttv = (TextView) v.findViewById(R.id.textviewer);   


    texttv.setText(Html.fromHtml(text));
    texttv.setMovementMethod(LinkMovementMethod.getInstance());

和textview onclicklistener:

texttv.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {

                switchToEditMode sw = new switchToEditMode();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

提前致谢,
西蒙

解决方法

我为你做了黑客攻击,试试这个代码吧!

说明:

1.使用自定义的ClickableSpan来处理点击网址.

2.clickablespan将在textview之前处理click事件,在单击链接时创建一个标志.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView textView = (TextView) findViewById(R.id.main_text);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    CharSequence charSequence = textView.getText();
    SpannableStringBuilder sp = new SpannableStringBuilder(charSequence);

    URLSpan[] spans = sp.getSpans(0,charSequence.length(),URLSpan.class);

    for (URLSpan urlSpan : spans) {
        MySpan mySpan = new MySpan(urlSpan.getURL());
        sp.setSpan(mySpan,sp.getSpanStart(urlSpan),sp.getSpanEnd(urlSpan),Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    }

    textView.setText(sp);

    textView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // 2.if clicking a link
            if (!isClickingLink) {
                Log.w("log","not clicking link");
            }
            isClickingLink = false;
        }
    });
}


private boolean isClickingLink = false;

private class MySpan extends ClickableSpan {

    private String mUrl;

    public MySpan(String url) {

        super();
        mUrl = url;
    }

    @Override
    public void onClick(View widget) {

        isClickingLink = true;
        // 1. do url click
    }

}
原文链接:https://www.f2er.com/android/314227.html

猜你在找的Android相关文章