2017-09-03 11 views
0

Android TextView 구성 요소에 대한 맞춤 링크를 만들고 '온 터치'동작을 처리하는 간단한 방법이 있습니까?맞춤 링크가있는 TextView

나는 인터넷에서 해결책을 찾지 못했지만 내 자신과 함께했습니다.

+0

[linkify] (https://stackoverflow.com/questions/4746293/android-linkify-textview)가 문제를 해결합니까? – isabsent

+0

Linkify의 경우 자신 만의 스키마를 구현해야하며 여전히 Touchmovement 메서드를 재정의하거나 터치 이벤트에 반응하기 위해 직접 작성해야합니다. 아래의 메서드는 프레임 워크의 Html 래퍼를 사용하는데 이는 매우 편리하다고 생각합니다. – Kvant

답변

0

터치 이벤트의 결과로 텍스트 뷰에 대한 맞춤 링크를 만들고 동작을 처리하는 간단한 방법이 있습니다. 패턴 랩퍼를 작성하고 작성하지 않으려면 Html 랩퍼가 사용됩니다.

TextView tView = ((TextView)v.findViewById(R.id.otp_activation_notification)); 
    Spanned ssBuilder = Html.fromHtml("Not a link <a href=\"foo://haha/arg1/arg2?q1=1&q2=2\">The first link</a> bla bla " 
    + " <a href=\"foo://haha2?q3=3\">The second link</a>"); 
    tView.setText(ssBuilder); 
    tView.setMovementMethod(new LinkMovementMethod(){ 

     @Override 
     public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { 
      //TODO: In order to override the links actions 
      int x = (int) event.getX(); 
      int y = (int) event.getY(); 

      Layout layout = widget.getLayout(); 
      int line = layout.getLineForVertical(y); 
      int off = layout.getOffsetForHorizontal(line, x); 

      try { 
       URLSpan[] urlSpans = buffer.getSpans(off, off, URLSpan.class); 
       if (urlSpans != null && urlSpans.length > 0) { 
        Uri uri = Uri.parse(urlSpans[0].getURL()); 
        String scheme = uri.getScheme(); 
        if ("foo".equals(scheme)) { 
         String command = uri.getAuthority(); 
         if ("haha".equals(command)) { 
          List<String> arguments = uri.getPathSegments(); 
          String q1 = uri.getQueryParameter("q1"); 
          String q2 = uri.getQueryParameter("q2"); 
          //TODO: Execute command (pay attention for MotionEvent) 
          return true; 
         } else if ("haha2".equals(command)) { 
          String q3 = uri.getQueryParameter("q2"); 
          //TODO: Execute command2 (pay attention for MotionEvent) 
          return true; 
         } 
         return false; 
        } 
       } 
      } catch (Exception e) { 
       //Log: unable to parse link; 
      } 
      //return false in case you don't want to use default behavior. 
      return super.onTouchEvent(widget, buffer, event); 

     } 
    });