箇条書きリストをAndroidアプリケーションに追加する方法は?


89

質問をグーグルで検索しましたが、有効な回答が提供されていません。テキストビューに箇条書きを追加するにはどうすればよいですか。

回答:


185

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
commonswareサイトへのリンクをありがとう、しばらくの間そのようなものを探していました!
ノーマンH

4
あなたは()context.getString(R.string.yourstringを使用して;)値/のstrings.xmlから文字列を取得している場合がありますのでご注意ください、あなたが持っているだろうが、それをラップするCDATA<string name="string_name"><![CDATA[ &#8226; foo<br /> &#8226; bar... ]]></string>
クエンティン・S.

5
箇条書き項目に複数の行がある場合、これは機能しません
thepoosh

それは次のようになりますul/ liサポートされるようになりましたstackoverflow.com/questions/9754076/...
HMAC

55
  1. browepは、HTMLを介した方法について説明しました。htmlエンティティで提供されるソリューションは有用な場合があります。しかし、それは弾丸だけを含みます。テキストが折り返されると、インデントが正しくなくなります。

  2. Webビューを埋め込む他のソリューションを見つけました。これは適切な場合もありますが、やりすぎだと思います...(リストビューを使用する場合も同様です)。

  3. 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));

ポジティブ:

  • テキストが折り返された後のインデントが正しい箇条書き。
  • TextViewの1つのインスタンスで、他のフォーマットされたテキストまたはフォーマットされていないテキストを組み合わせることができます
  • BulletSpanコンストラクターで、インデントの大きさを定義できます。

負:

  • リストのすべてのアイテムを個別の文字列リソースに保存する必要があります。だからあなたはあなたがHTMLでどのように快適にできるかあなたのリストを定義することはできません。

1
このアプローチ(正確に模倣)は2.2では機能しません。あなたはたった1つの弾丸で終わります。
スコーン、2011

こんにちはSkone。2.2エミュレータとオリジナルのAndroidビルドで動作します。箇条書きとテキストの間のスペースが無視されたAndroidバージョンを見ました。しかし、弾丸はまだ現れました。弾丸ストリングの最後に改行がありますか?
Diego Frehner、2009

この解決策は、テキストビューの行間を変更すると機能しません
Marqs

BulletSpanでそれを行う素晴らしい方法は、完璧に機能し、非常に簡単です!
Moonbloom

7
上記のコードは私のために動作します!!! 私がしなければならなかったすべてはxmlのすべての文字列の終わりに "\ n"を追加することです...
Arhat Baid

38

この箇条書き "•"(テキスト)をコピーしてテキストビューのテキストに貼り付けるだけで、代替テキストが見つかります。テキストの色や、サイズ、高さ、幅など、他のすべての属性を変更して、箇条書きの色を変更できます。 .. :)

入力中にショートカットを使用してこの弾丸を取得できます

窓用

Alt + 7

Mac用

Alt + 8


2
Alt + 7は私には機能しません(おそらくMacまたはLinuxのものだけです)が、Unicode文字をコピーして貼り付けることはできました。
Jon

2
参考:ALT + 7は、キーボードに個別のテンキーがある場合にのみ機能します。
Aks4125 2016年

シンボルをコード、つまり文字列に貼り付ける場合は、非ASCII文字とファイルエンコーディングの問題に注意してください(IntelliJの右下隅からファイルのエンコーディングを変更してみてください)。対応するエスケープシーケンス(\ u1234など)を使用することをお勧めします。
Gil Vegliach 2016年

行く方法!!ごろつきライフ!
goonerDroid 2017年

2
\ u2022が答えである
user2322082

21

ここでのさまざまな答えに触発されて、これを簡単なワンライナーにするためのユーティリティクラスを作成しました。これにより、折り返されたテキストのインデント付きの箇条書きが作成されます。文字列、文字列リソース、文字列配列リソースを組み合わせるためのメソッドがあります。

TextViewに渡すことができるCharSequenceを作成します。例えば:

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

お役に立てば幸いです。楽しい。

注:これは、システム標準の箇条書き、テキストと同じ色の小さな円を使用します。カスタムの弾丸が必要な場合は、BulletSpanをサブクラス化してdrawLeadingMargin()必要な弾丸を描画するようにオーバーライドすることを検討してください。どのように機能するかについてはBulletSpanのソースご覧ください。

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;
}

}

どうもありがとうございました!私はmakeBulletList関数を使用しましたが、それは魅力のように機能します:D
Aba

それは素晴らしいです!ありがとう)
kulikovman

10

これははるかに簡単です。

<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>

8

すぐに使えるKotlin拡張機能

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
        }
    }
}

使用法:

val bulletedList = listOf("One", "Two", "Three").toBulletedList()
label.text = bulletedList

色とサイズ:

弾丸の色またはサイズを変更するには、BulletSpanの代わりにCustomBulletSpanを使用します

package com.fbs.archBase.ui.spans

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.Layout
import android.text.Spanned
import android.text.style.LeadingMarginSpan
import androidx.annotation.ColorInt

class CustomBulletSpan(
        private val bulletRadius: Int = STANDARD_BULLET_RADIUS,
        private val gapWidth: Int = STANDARD_GAP_WIDTH,
        @ColorInt private val circleColor: Int = STANDARD_COLOR
) : LeadingMarginSpan {

    private companion object {
        val STANDARD_BULLET_RADIUS = Screen.dp(2)
        val STANDARD_GAP_WIDTH = Screen.dp(8)
        const val STANDARD_COLOR = Color.BLACK
    }

    private val circlePaint = Paint().apply {
    color = circleColor
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    override fun getLeadingMargin(first: Boolean): Int {
        return 2 * bulletRadius + gapWidth
    }

    override fun drawLeadingMargin(
            canvas: Canvas, paint: Paint, x: Int, dir: Int,
            top: Int, baseline: Int, bottom: Int,
            text: CharSequence, start: Int, end: Int,
            first: Boolean,
            layout: Layout?
    ) {
        if ((text as Spanned).getSpanStart(this) == start) {
            val yPosition = (top + bottom) / 2f
            val xPosition = (x + dir * bulletRadius).toFloat()

            canvas.drawCircle(xPosition, yPosition, bulletRadius.toFloat(), circlePaint)
        }
    }
}

弾丸のサイズをテキストサイズに一致するように変更できますか?
nenur

@NoahTanenholtzでは、BulletSpan()引数の値を変更することで弾丸のサイズを大きくできます
ミハイルシャリン

ああ、それはスペースだと思った
nenur

弾丸サイズの代わりに間隔が拡大されました):
Sumit Shukla

@SumitShuklaコメントありがとうございます。色とサイズのカスタマイズにBulletCustomSpanを追加しました
ミハイルシャリン

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" />

ドローアブルのウェブから小さな弾丸の写真をつかんだところです。Eclipseのグラフィカルレイアウトでは、テキストの下に引き伸ばされたグラフィックが表示されます。
JohnK

1
私は彼が意味したと思いますandroid:drawableLeft=
Blundell

4

複合ドローアブルでシンプルなTextViewを使用します。例えば

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

3

これは別の解決策です。リストを1つのテキストビューに正確に追加するわけではありませんが、目標は同じだと思います。それはXMLのみを必要とするTableLayoutを使用しており、小さい順序付けされたリストまたは順序付けされていないリストに対しては非常に簡単です。以下は、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>

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();
    }

}

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);
    }

}

弾丸のサイズと間隔を増やすにはどうすればよいですか?
Sumit Shukla

この例では、&#8226;別のシンボルfsymbols.com/signs/bullet-point
Blundell

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"));
}

1

箇条書きリストは、文字列リソースのタグ<ul><li>タグを使用して簡単に作成できます。

コードで文字列を設定するためにsetText(Html.fromHtml(string))使用しないでください!通常はxmlで、またはsetText(string)を使用して文字列を設定します。

例えば:

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


次のタグは、このようにサポートされています(文字列リソースに直接埋め込まれています)。

  • <a>(属性 "href"をサポート)
  • <注釈>
  • <b>
  • <大きい>
  • <font>(整数として、属性「height」、「size」、「fgcolor」、および「bicolor」をサポートします)
  • <私>
  • <li>
  • <マーキー>
  • <小>
  • <ストライク>
  • <サブ>
  • <sup>
  • <tt>
  • <u>

あなたは必要ありません<ul>
Blundell

5
動作しません。サポートされるhtmlタグは、<b>、<i>、および<u>のみです。developer.android.com/guide/topics/resources/...
Wooff

私には完璧に働きました!すべてを機能させるために私がしなければならなかった唯一のことは、各行の先頭に\ n置くことでした。ie\n<ul><li>a</li> \n<li>b</li> \n<li>c</li></ul>
ジャックT

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あなたの条件に基づきます。


0

箇条書きを行うための2つのオプションは次のとおりです。

  • html(ul、ol)を使用してリストを作成し、htmlをWebViewにロードします
  • データをListViewに読み込み、リストアイテムレイアウトのテキストビューの左側のドローアブルを、箇条書きに適した画像に設定します。

オプション1が最も簡単です。



0

editText構造で箇条書きリストを作成したい場合。

私はこの参照を利用しました

この弾丸を使用できます

           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());
                    }
                }
            }
        });
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.