2017-09-05 2 views
9

와 특수 문자를 얻을 : 내가하고 싶었던 것을내가 어떻게이 같은 3 문자열이 단어와 클릭 이벤트

"@Username: Deliverd your order", 
"YOU got trophy: KING OF COINS", 
"There is a package waiting for you to pick up from #surat to #mumbai", 

는 클릭 이벤트와 다른 색으로 사용자 이름과 도시 이름을 얻을 수 있습니다.

나는 ":"문자로 나눠서 사용자 이름을 얻을 수 있습니다. 하지만 도시 이름을 얻고 두 이벤트를 모두 알 수는 없습니다.

도시 이름은 도시 이름 색상 만 변경하고 클릭 이벤트는 어떻게 변경합니까?

if (notifications.getTitle().contains(":")) 
{ 
    String[] username = notifications.getTitle().split(":"); 
    String uname = getColoredSpanned(username[0] + ":", "#ff7505"); 
    String txt = getColoredSpanned(username[1], "#000000"); 
    holder.txtTitle.append(Html.fromHtml(uname +" " + txt)); 
    holder.txtTitle.setMovementMethod(LinkMovementMethod.getInstance()); 
} 
else if (notifications.getTitle().contains("#")) 
{ 
    Matcher matcher = 
      Pattern.compile("#\\s(\\w+)").matcher(notifications.getTitle()); 
    i=0; 
    while (matcher.find()) 
    { 
      place.add(i, matcher.group(1)); 
      i++; 
    } 
    String place1 = getColoredSpanned("#" + place.get(0), "#237BCD"); 
    String place2 = getColoredSpanned("#" + place.get(1), "#237BCD"); 
    places1 = notifications.getTitle().replace("#" + place.get(0), place1); 
    places1 = notifications.getTitle().replace("#" + place.get(1), place2); 
    holder.txtTitle.setText(Html.fromHtml(places1)); 
} 
else 
{ 
    holder.txtTitle.setText(notifications.getTitle()); 
} 

private String getColoredSpanned(String text, String color) { 
    String input = "<font color=" + color + ">" + text + "</font>"; 
    return input; 
} 

이 내가 출력으로 무엇을 얻을 :

내가 뭘하려

enter image description here

을이 정말 기대했던 것입니다 :

enter image description here

+0

https://stackoverflow.com/questions/10696986/how-to-set-the-part-of-the-text-view-is-clickable – vlatkozelka

+0

텍스트에서 데이터를 가져 오는 방법은 포맷을 시도해보십시오. 당신의 문자열을 split(), 아마도 json을 사용하기보다는 구문 분석하기가 더 쉽다. – vlatkozelka

+0

나는 귀하의 링크를 시도했지만 클릭 이벤트를 얻을 수 있지만 색상을 설정할 수 없습니다. –

답변

3

난 당신이 내가 도시 이름에 클릭으로 답변을 준 도시 클릭으로 사용자 이름과 직면 문제를했을 것 같아요.

@Vinay에게 감사드립니다.

아래 코드를 확인하십시오.

public void setSpan() { 
     String test = "There is a package waiting for you to pick up from #surat to #mumbai"; 
     SpannableString spannable = new SpannableString(test); 
     final Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(test); 
     while (matcher.find()) { 
      final String city = matcher.group(1); 
      ClickableSpan clickableSpan = new ClickableSpan() { 
       @Override 
       public void onClick(View textView) { 
        Toast.makeText(mActivity, city, Toast.LENGTH_SHORT).show(); 
       } 

       @Override 
       public void updateDrawState(TextPaint ds) { 
        super.updateDrawState(ds); 
        ds.setUnderlineText(false); 
        ds.setColor(Color.RED); 
       } 
      }; 
      int cityIndex = test.indexOf(city) - 1; 
      spannable.setSpan(clickableSpan, cityIndex, cityIndex + city.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
     } 
     mTextViewNotification.setText(spannable); 
     mTextViewNotification.setMovementMethod(LinkMovementMethod.getInstance()); 
    } 

출력 스크린 샷 :

enter image description here

+0

은 "#"에서만 작동합니까? "$"기호가있는 다른 텍스트가 있고, 일치하지 않는 doller 기호 패턴이 있기 때문입니다. –

+0

그리고 "@"기호는 항상 java.lang.IndexOutOfBoundsException과 같은 오류가 발생합니다. setSpan (-2 ... 7)이 0보다 먼저 시작됩니다. –

+0

이 논리를이 ** else if (notifications.getTitle(). ** 섹션 –

4

이것을 위해 Regex를 사용하십시오.

String str= "There is a package waiting for you to pick up from #surat to #mumbai"; 

Matcher matcher = Pattern.compile("#\\s*(\\w+)").matcher(str); 
while (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

출력은 다음과 같습니다

surat 
mumbai 
+0

하지만 최종 문자열을 만드는 방법은 ..., 솔루션을 적용한 결과, 나는 수랏과 뭄바이를 얻었습니다. 출력, 나는 또한 두 장소에 색깔, 이제는 최종 출력으로 textview에 추가하는 방법 –

4

이 목록의 항목 레이아웃에 숨겨진 LinearLayout를 추가, 클릭 해시 태그와 최종 설명을 추출하려면 :

<LinearLayout 
     android:id="@+id/layoutDescription" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="24dp" 
     android:orientation="horizontal" 
     android:visibility="gone" /> 

을 별도의 코드를 수정 해시 태그를 동적 인 TextViews과 함께 추가하고 LinearLayout에 다시 추가합니다.

,451,515,

최종 출력

if (notifications.getTitle().contains(":")) { 
     String[] username = notifications.getTitle().split(":"); 
     String pre_username = getColoredSpanned(username[0] + ":", "#ff7505"); 
     String post_username = getColoredSpanned(username[1], "#000000"); 
     holder.txtTitle.append(Html.fromHtml(pre_username + " " + post_username)); 
     holder.txtTitle.setMovementMethod(LinkMovementMethod.getInstance()); 
    } 
    else if (notifications.getTitle().contains("#")) { 
     layoutDescription.setVisibility(View.VISIBLE); 

     Matcher matcher = Pattern.compile("#\\s(\\w+)").matcher(notifications.getTitle()); 

     List<String> place = new ArrayList<>(); 
     int i = 0; 
     while (matcher.find()) { 
      place.add(i, matcher.group(1)); 
      i++; 
     } 

     LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     layoutParams.setMargins(5, 0, 5, 0); // (left, top, right, bottom) 

     TextView mHashTagA = new TextView(this); 
     mHashTagA.setLayoutParams(layoutParams); 
     mHashTagA.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Toast.makeText(getApplicationContext(), "Clicked on HashTag A", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     TextView mSeparator = new TextView(this); 
     mSeparator.setLayoutParams(layoutParams); 
     mSeparator.setText("to"); 

     TextView mHashTagB = new TextView(this); 
     mHashTagB.setLayoutParams(layoutParams); 
     mHashTagB.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Toast.makeText(getApplicationContext(), "Clicked on HashTag B", Toast.LENGTH_SHORT).show(); 
      } 
     }); 

     TextView mDescription = new TextView(getApplicationContext()); 
     mDescription.setTextColor(Color.parseColor("#343434")); 
     mDescription.setLayoutParams(layoutParams); 

     String place1 = getColoredSpanned("#" + place.get(0), "#237BCD"); 
     mHashTagA.setText(Html.fromHtml(place1)); 

     String place2 = getColoredSpanned("#" + place.get(1), "#237BCD"); 
     mHashTagB.setText(Html.fromHtml(place2)); 

     String without_hash = notifications.getTitle().split("#")[0]; 
     mDescription.setText(without_hash); 

     layoutDescription.addView(mDescription); 
     layoutDescription.addView(mHashTagA); 
     layoutDescription.addView(mSeparator); 
     layoutDescription.addView(mHashTagB); 
    } else { 
     layoutDescription.setVisibility(View.GONE); 
     holder.txtTitle.setText(notifications.getTitle()); 
    } 
,

enter image description here

+0

완벽한 답변처럼 보입니다. –

+0

유망한 것 같습니다. 나는 곧 시도 할거야. 그리고 사용자 클릭 이벤트에 대해서는 –

+0

멀티 라인 텍스트에서는 작동하지 않을 것이다. –

1

사용 SpannableString는 youd가 바로 클릭 할 수있는 단어 색인을 알고, 어떤 특수 문자가 필요하지 않습니다. 벨로우즈처럼 :

SpannableString styledString 
      = new SpannableString("There is a package waiting for you to pick up from " + 
      "surat" + // index 51 - 56 
      " to " + 
      "mumbai"); //index 60 - 66 

    // clickable text for "surat" 
    ClickableSpan clickableSpan1 = new ClickableSpan() { 

     @Override 
     public void onClick(View widget) { 
      // We display a Toast. You could do anything you want here. 
      Toast.makeText(MainActivity.this, "surat clicked", Toast.LENGTH_SHORT).show(); 

     } 
    }; 

    // clickable text for "mumbai" 
    ClickableSpan clickableSpan2 = new ClickableSpan() { 

     @Override 
     public void onClick(View widget) { 
      // We display a Toast. You could do anything you want here. 
      Toast.makeText(MainActivity.this, "mumbai clicked", Toast.LENGTH_SHORT).show(); 

     } 
    }; 

    styledString.setSpan(clickableSpan1, 51, 56, 0); 
    styledString.setSpan(clickableSpan2, 60, 66, 0); 

    textView.setText(styledString); 
+0

나도 알아, 그 일반적인 일은 .. 내 텍스트가 동적입니다 .. –

3

시도 this library. # 만 작동하는 해시 태그 구현입니다. 이 라이브러리를 요구 사항에 맞게 개선하면 도움이 될 수 있습니다.

+1

좋은 라이브러리 ... 예 도움이 될 수 있습니다 ... 감사합니다. –