如何将项目符号列表添加到Android应用程序?

时间:2011-02-14 13:38:23

标签: android textview

我搜索了我的问题,但没有提供有效的答案。如何在我的textview中添加项目符号列表。

17 个答案:

答案 0 :(得分:173)

不支持ul / li / ol。幸运的是,您可以将其用作语法糖:

&#8226; foo<br/>
&#8226; bar<br/>
&#8226; baz<br/>

&#8226;是列表项目符号的html实体 这里有更多选择http://www.elizabethcastro.com/html/extras/entities.html

更多关于Mark Murphy(@CommonsWare)提供支持的标签 http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html 用Html.fromHtml加载它

((TextView)findViewById(R.id.my_text_view)).setText(Html.fromHtml(myHtmlString));

答案 1 :(得分:49)

  1. browep explained nice the way over HTML.提供的html实体解决方案非常有用。但它只包括子弹。如果您的文字换行,则缩进将不正确。

  2. 我找到了嵌入网络视图的其他解决方案。这对某些人来说可能是合适的,但我认为它有点矫枉过正......(与使用列表视图相同。)

  3. 我喜欢creative approach of Nelson:D,但它不会让您将无序列表添加到文本视图中。

  4. 使用BulletSpan

    的带有项目符号的无序列表的示例
    CharSequence t1 = getText(R.string.xxx1);
    SpannableString s1 = new SpannableString(t1);
    s1.setSpan(new BulletSpan(15), 0, t1.length(), 0);
    CharSequence t2 = getText(R.string.xxx2);
    SpannableString s2 = new SpannableString(t2);
    s2.setSpan(new BulletSpan(15), 0, t2.length(), 0);
    textView.setText(TextUtils.concat(s1, s2));
    
  5. 正:

    • 文本换行后缩进正确的项目符号。
    • 您可以在TextView
    • 的一个实例中组合其他格式化或未格式化的文本
    • 您可以在BulletSpan构造函数中定义缩进的大小。

    阴性:

    • 您必须将列表中的每个项目保存在单独的字符串资源中。因此,您无法定义符合HTML格式的列表。

答案 2 :(得分:30)

我找到了一个替代品......只需复制此子弹“•”(它是一个文本)并粘贴到文本视图的文本中,您可以通过更改文本颜色以及所有其他属性(如大小)来更改项目符号颜色,身高......:)

您可以在输入

时使用快捷方式获取此项目符号

for windows

  

ALT + 7

for mac

  

ALT + 8

答案 3 :(得分:19)

受到各种答案的启发,我创建了一个实用程序类,使其成为一个简单的单行。这将创建一个带有包装文本缩进的项目符号列表。 它具有组合字符串,字符串资源和字符串数组资源的方法。

它将创建一个CharSequence,您可以将其传递给TextView。例如:

CharSequence bulletedList = BulletListUtil.makeBulletList("First line", "Second line", "Really long third line that will wrap and indent properly.");
textView.setText(bulletedList);

希望它有所帮助。享受。

注意:这将使用系统标准项目符号,一个与文本颜色相同的小圆圈。如果您需要自定义项目符号,请考虑继承BulletSpan并覆盖其drawLeadingMargin()以绘制所需的项目符号。请查看BulletSpan source,了解其工作原理。

public class BulletTextUtil {

/**
 * Returns a CharSequence containing a bulleted and properly indented list.
 *
 * @param leadingMargin In pixels, the space between the left edge of the bullet and the left edge of the text.
 * @param context
 * @param stringArrayResId A resource id pointing to a string array. Each string will be a separate line/bullet-point.
 * @return
 */
public static CharSequence makeBulletListFromStringArrayResource(int leadingMargin, Context context, int stringArrayResId) {
    return makeBulletList(leadingMargin, context.getResources().getStringArray(stringArrayResId));
}

/**
 * Returns a CharSequence containing a bulleted and properly indented list.
 *
 * @param leadingMargin In pixels, the space between the left edge of the bullet and the left edge of the text.
 * @param context
 * @param linesResIds An array of string resource ids. Each string will be a separate line/bullet-point.
 * @return
 */
public static CharSequence makeBulletListFromStringResources(int leadingMargin, Context context, int... linesResIds) {
    int len = linesResIds.length;
    CharSequence[] cslines = new CharSequence[len];
    for (int i = 0; i < len; i++) {
        cslines[i] = context.getString(linesResIds[i]);
    }
    return makeBulletList(leadingMargin, cslines);
}

/**
 * Returns a CharSequence containing a bulleted and properly indented list.
 *
 * @param leadingMargin In pixels, the space between the left edge of the bullet and the left edge of the text.
 * @param lines An array of CharSequences. Each CharSequences will be a separate line/bullet-point.
 * @return
 */
public static CharSequence makeBulletList(int leadingMargin, CharSequence... lines) {
    SpannableStringBuilder sb = new SpannableStringBuilder();
    for (int i = 0; i < lines.length; i++) {
        CharSequence line = lines[i] + (i < lines.length-1 ? "\n" : "");
        Spannable spannable = new SpannableString(line);
        spannable.setSpan(new BulletSpan(leadingMargin), 0, spannable.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(spannable);
    }
    return sb;
}

}

答案 4 :(得分:5)

这是迄今为止最简单的..

<string name="bullet_ed_list">\n\u2022 He has been Chairman of CFL Manufacturers Committee of ELCOMA, the All India Association of Lighting Equipment Manufacturers.
\n\u2022 He has been the President of Federation of Industries of India (FII).</string>

答案 5 :(得分:4)

我使用的一个选项是使用样式设置子弹可绘制。

<style name="Text.Bullet">
    <item name="android:background">@drawable/bullet</item>
    <item name="android:paddingLeft">10dp</item>
</style>

用法:

<TextView android:id="@+id/tx_hdr" 
android:text="Item 1" style="@style/Text.Bullet" />

答案 6 :(得分:4)

即用型Kotlin扩展程序

Error while compiling statement: FAILED: ParseException line 28:0 missing EOF at 'lateral' near 'id_notification'

用法:

fun List<String>.toBulletedList(): CharSequence {
    return SpannableString(this.joinToString("\n")).apply {
        this@toBulletedList.foldIndexed(0) { index, acc, span ->
            val end = acc + span.length + if (index != this@toBulletedList.size - 1) 1 else 0
            this.setSpan(BulletSpan(16), acc, end, 0)
            end
        }
    }
}

答案 7 :(得分:4)

使用带有复合drawable的简单TextView。例如

<TextView     
    android:text="Sample text"
    android:drawableLeft="@drawable/bulletimage" >
</TextView>

答案 8 :(得分:3)

这是另一个解决方案,不是将列表添加到一个textview,但我猜目标是相同的。它使用TableLayout,它只需要XML,对于小的有序或无序列表来说它非常简单。下面是我用于此的示例代码,而不是Java中的一行代码。

正:

  • 您可以在表格行中放置任何您喜欢的内容,而不必是textview
  • 您可以使用它来创建项目符号和编号列表或其他
  • 您可以使用padding或layout_weight
  • 定义缩进

阴性:

  • 很长的列表很繁琐(除非你使用一些狡猾的文本编辑器与正则表达式)
  • 每个列表项都存储为单独的字符串资源

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
    
            >
    
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="0.2"
                android:text="1." />
    
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="3"
                android:text="@string/help_points1" />
        </TableRow>
    
        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            >
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="0.2"
                android:text="2." />
    
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="3"
                android:text="@string/help_points2" />
        </TableRow>
        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            >
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="0.2"
                android:text="3." />
            <TextView
                style="@style/helpPagePointsStyle"
                android:layout_weight="3"
                android:text="@string/help_points3" />
        </TableRow>
    
    
    </TableLayout>
    

和风格:

<style name="helpPagePointsStyle">
    <item name="android:layout_width">0dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:gravity">left</item>
</style>

答案 9 :(得分:2)

完全矫枉过正并制作了自定义文字视图。

像这样使用:

<com.blundell.BulletTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="--bullet 1 --bullet two --bullet three --bullet four" />

和代码:

package com.blundell;

import android.content.Context;
import android.text.Html;
import android.util.AttributeSet;
import android.widget.TextView;

public class BulletTextView extends TextView {
    private static final String SPLITTER_CHAR = "--";
    private static final String NEWLINE_CHAR = "<br/>";
    private static final String HTML_BULLETPOINT = "&#8226;";

    public BulletTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public BulletTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        checkForBulletPointSplitter();
    }

    private void checkForBulletPointSplitter() {
        String text = (String) getText();
        if (text.contains(SPLITTER_CHAR)) {
            injectBulletPoints(text);
        }
    }

    private void injectBulletPoints(String text) {
        String newLinedText = addNewLinesBetweenBullets(text);
        String htmlBulletText = addBulletPoints(newLinedText);
        setText(Html.fromHtml(htmlBulletText));
    }

    private String addNewLinesBetweenBullets(String text) {
        String newLinedText = text.replace(SPLITTER_CHAR, NEWLINE_CHAR + SPLITTER_CHAR);
        newLinedText = newLinedText.replaceFirst(NEWLINE_CHAR, "");
        return newLinedText;
    }

    private String addBulletPoints(String newLinedText) {
        return newLinedText.replace(SPLITTER_CHAR, HTML_BULLETPOINT);
    }

}

答案 10 :(得分:2)

这是一个项目符号列表,每个项目前面都有一个标题和一个标签。

public class BulletListBuilder {

    private static final String SPACE = " ";
    private static final String BULLET_SYMBOL = "&#8226";
    private static final String EOL = System.getProperty("line.separator");
    private static final String TAB = "\t";

    private BulletListBuilder() {

    }

    public static String getBulletList(String header, String []items) {
        StringBuilder listBuilder = new StringBuilder();
        if (header != null && !header.isEmpty()) {
            listBuilder.append(header + EOL + EOL);
        }
        if (items != null && items.length != 0) {
            for (String item : items) {
                Spanned formattedItem = Html.fromHtml(BULLET_SYMBOL + SPACE + item);
                listBuilder.append(TAB + formattedItem + EOL);
            }
        }
        return listBuilder.toString();
    }

}

答案 11 :(得分:1)

我发现这是最简单的方法,将textView保留在xml文件中并使用以下java代码。它对我来说非常好。

private static final String BULLET_SYMBOL = "&#8226";

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tutorial);

    TextView tv = (TextView) findViewById(R.id.yourTextView);

    tv.setText("To perform this exercise you will need the following: "
                        + System.getProperty("line.separator")//this takes you to the next Line
                        + System.getProperty("line.separator")
                        + Html.fromHtml(BULLET_SYMBOL + " Bed")
                        + System.getProperty("line.separator")
                        + Html.fromHtml(BULLET_SYMBOL + " Pillow"));
}

答案 12 :(得分:1)

对于single line text,您可以简单地使用可绘制对象:

<TextView
    android:id="@+id/txtData"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableStart="@drawable/draw_bullet_list"
    android:drawablePadding="@dimen/padding_8dp"
    android:text="Hello"
    android:textColor="@color/colorBlack" />

draw_bullet_list.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/colorAccent" />

    <size
        android:width="12dp"
        android:height="12dp" />

</shape>

您可以根据需要更改shapesizecolor

答案 13 :(得分:0)

支持缺少HTML标记的另一种方法是将其更换为here

答案 14 :(得分:0)

执行项目符号列表的两个选项是

  • 使用html(ul,ol)创建列表并将html加载到WebView
  • 将数据加载到ListView中,并将列表项布局中文本视图的左侧drawable设置为子弹的合适图像。

选项1是最简单的。

答案 15 :(得分:0)

可以使用字符串资源中的<ul><li>标记简单地创建项目符号列表。

请勿使用 setText(Html.fromHtml(string))在代码中设置字符串!只需在xml中正常设置字符串或使用setText( string )。

E.g:

strings.xml文件

<string name="str1"><ul> <li><i>first</i> item</li> <li>item 2</li> </ul></string>


layout.xml文件

    <TextView
        android:text="@string/str1"
    />


它将产生以下结果:

  • 第一个项目
  • 第2项


像这样支持以下标记(直接嵌入在字符串资源中):

  • &LT a取代; (支持属性“href”)
  • &LT;注释&GT;
  • &LT b取代;
  • &LT;大&GT;
  • &LT;字体&GT; (支持属性“height”,“size”,“fgcolor”和“bicolor”,作为整数)
  • &LT; I&GT;
  • &LT;李&GT;
  • &LT;选取框&GT;
  • &LT;小&GT;
  • &LT;击&GT;
  • &lt;副&GT;
  • &LT;坐席&GT;
  • &LT; TT&GT;
  • &LT; U&GT;

答案 16 :(得分:0)

如果要创建带有editText结构的项目符号列表。

我从这个references受益

您可以使用此bullets

           EditText  edtNoteContent = findViewById(R.id.editText_description_note);            

        edtNoteContent.addTextChangedListener(new TextWatcher(){
            @Override
            public void afterTextChanged(Editable e) {

            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }
            @Override
            public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter)
            {
                if (lengthAfter > lengthBefore) {
                    if (text.toString().length() == 1) {
                        text = "◎ " + text;
                        edtNoteContent.setText(text);
                        edtNoteContent.setSelection(edtNoteContent.getText().length());
                    }
                    if (text.toString().endsWith("\n")) {
                        text = text.toString().replace("\n", "\n◎ ");
                        text = text.toString().replace("◎ ◎", "◎");
                        edtNoteContent.setText(text);
                        edtNoteContent.setSelection(edtNoteContent.getText().length());
                    }
                }
            }
        });
相关问题