Search code examples
androidtextviewspannablestring

SpannableString is not working in a Dialog


I want to show the spanString in Bold style and rest of the string in normal style in TextView. But the whole TextView showed in normal style only. Please help me.

if ((mStoreListValue.get(pos).getStoreStatus().equals("CLOSED"))){

   final Dialog dialog = new Dialog(v.getRootView().getContext(), android.R.style.Theme_Translucent_NoTitleBar);
   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
   dialog.getWindow().setContentView(R.layout.resclosed_dialog);
   ImageView btn_close =  dialog.findViewById(R.id.close_btn);
   TextView txt_close =  dialog.findViewById(R.id.tv_closed);

   SpannableString spanString = new SpannableString(sname);
   spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

   txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));

   btn_close.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
              dialog.dismiss();
         }
    });
  dialog.show();

Solution

  • Use this

    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString spanString = new SpannableString(sname);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    builder.append(spanString);
    builder.append(mContext.getResources().getString(R.string.closed));
    txt_close.setText(builder);
    

    Instead of this

    txt_close.setText(spanString +  " " + mContext.getResources().getString(R.string.closed));