问题
I wanted to show bullets in android text. I have added them successfully. I search over internet and found that you can add bullets. but if text goes more than one line it does not follow proper spacing like html list does.
See Screenshot below.
I have used following code to add bullets.
String longDescription = "Enhanced bass performance.\n" +
"Lightweight headband enhances comfort and adds durability\n" +
"Easy to adjust headband ensures optimum fit and comfort\n" +
"2 metre-long cable";
String arr[] = longDescription.split("\n");
StringBuilder desc = new StringBuilder();
for (String s : arr){
desc.append("<li>"+s+"</li>");
}
String newDesc = "<ul>"+desc+"</ul>";
tvProdDesc.setText(Html.fromHtml(newDesc, null, new UlTagHandler()));
Here is my
UlTagHandler.java
public class UlTagHandler implements Html.TagHandler {
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if(tag.equals("ul") && !opening) output.append("\n");
if(tag.equals("li") && opening) output.append("\n•\t");
}
}
But I want text should be properly formatted like word processor does.
I want this type of output
Can we do anything simillar to above image?
回答1:
Would You be satisfied of this example?
public class MainActivity extends AppCompatActivity {
private TextView tvProdDesc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvProdDesc = (TextView) findViewById(R.id.text1);
String longDescription = "Enhanced bass performance.\n" +
"Lightweight headband enhances comfort and adds durability\n" +
"Easy to adjust headband ensures optimum fit and comfort\n" +
"2 metre-long cable";
String arr[] = longDescription.split("\n");
int bulletGap = (int) dp(10);
SpannableStringBuilder ssb = new SpannableStringBuilder();
for (int i = 0; i < arr.length; i++) {
String line = arr[i];
SpannableString ss = new SpannableString(line);
ss.setSpan(new BulletSpan(bulletGap), 0, line.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ssb.append(ss);
//avoid last "\n"
if(i+1<arr.length)
ssb.append("\n");
}
tvProdDesc.setText(ssb);
}
private float dp(int dp) {
return getResources().getDisplayMetrics().density * dp;
}
}
Result:
来源:https://stackoverflow.com/questions/40990755/add-bullets-with-proper-formatting-in-android