Android缩进和悬挂缩进

前端之家收集整理的这篇文章主要介绍了Android缩进和悬挂缩进前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有兴趣拥有一系列TextView,最终有一个悬挂缩进.通过CSS执行此操作的标准方法是将边距设置为X像素,然后将文本缩进设置为-X像素.显然我可以用“ android:layout_marginLeft =”Xdp“来做第一个,但我不知道如何在TextView上施加-X像素.任何想法或解决方法?我感谢任何建议.

解决方法

弄清楚如何使悬挂缩进适用于我自己的项目.基本上你需要使用android.text.style.LeadingMarginSpan,并通过代码将它应用到你的文本. LeadingMarginSpan.Standard采用完整缩进(1个参数)或悬挂缩进(2个参数)构造函数,并且需要为要应用样式的每个子字符串创建新的Span对象. TextView本身也需要将其BufferType设置为SPANNABLE.

如果必须多次执行此操作,或者希望在样式中包含缩进,请尝试创建TextView的子类,该子类采用自定义缩进属性自动应用跨度.我从Statically Typed博客和SO问题Declaring a custom android UI element using XML中获得了很多用途.

在TextView中:

  1. // android.text.style.CharacterStyle is a basic interface,you can try the
  2. // TextAppearanceSpan class to pull from an existing style/theme in XML
  3.  
  4. CharacterStyle style_char =
  5. new TextAppearanceSpan (getContext(),styleId);
  6. float textSize = style_char.getTextSize();
  7.  
  8. // indentF roughly corresponds to ems in dp after accounting for
  9. // system/base font scaling,you'll need to tweak it
  10.  
  11. float indentF = 1.0f;
  12. int indent = (int) indentF;
  13. if (textSize > 0) {
  14. indent = (int) indentF * textSize;
  15. }
  16.  
  17. // android.text.style.ParagraphStyle is a basic interface,but
  18. // LeadingMarginSpan handles indents/margins
  19. // If you're API8+,there's also LeadingMarginSpan2,which lets you
  20. // specify how many lines to count as "first line hanging"
  21.  
  22. ParagraphStyle style_para = new LeadingMarginSpan.Standard (indent);
  23.  
  24. String unstyledSource = this.getText();
  25.  
  26. // SpannableString has mutable markup,with fixed text
  27. // SpannableStringBuilder has mutable markup and mutable text
  28.  
  29. SpannableString styledSource = new SpannableString (unstyledSource);
  30. styledSource.setSpan (style_char,styledSource.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  31. styledSource.setSpan (style_para,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
  32.  
  33. // *or* you can use Spanned.SPAN_PARAGRAPH for style_para,but check
  34. // the docs for usage
  35.  
  36. this.setText (styledSource,BufferType.SPANNABLE);

猜你在找的Android相关文章