有谁知道如何在 ANDROID 布局中证明文本视图内容的合理性?

发布于 2024-09-15 14:52:06 字数 76 浏览 8 评论 0原文

我一直在使用 android:gravity 属性,但仍然无法使我的文本内容在文本视图中合理。有人知道是否支持吗?有办法吗?有人成功了吗?

I have been playing with android:gravity attribut but still cannot make my text content justify in the textview. Does anybody know if it is supported ? Is there a way ? Anybody succeeded ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

听你说爱我 2024-09-22 14:52:06

Android 似乎不支持完整的 Justification。 :(

你能实现的最好方法是左对齐或右对齐。

Android TextView 对齐文本

It would appear that Android does not support full Justification. :(

The best you can achieve is Left or Right Justification.

Android TextView Justify Text

迷离° 2024-09-22 14:52:06

您还可以设置 TextView 的宽度来包裹其内容(“wrap_content”)并在其父布局中对齐 TextView。

You could also make the width of the TextView to wrap its content ("wrap_content") and justify the TextView in its parent Layout.

小耗子 2024-09-22 14:52:06

使用以下代码:

        public class TextJustify {

        final static String SYSTEM_NEWLINE = "\n";
        final static float COMPLEXITY = 5.12f; // Reducing this will increase
                                     // efficiency but will decrease
                                    // effectiveness
        final static Paint p = new Paint();

        /* @author Mathew Kurian */

   public static void run(final TextView tv, float origWidth, 
          int paddingLeft, int   paddingRight, int marginLeft, int marginRight) {


    origWidth-= paddingRight+marginRight+paddingLeft+marginLeft;
    String s = tv.getText().toString();
    p.setTypeface(tv.getTypeface());
    String[] splits = s.split(SYSTEM_NEWLINE);
    float width = origWidth - 5;
    for (int x = 0; x < splits.length; x++)
        if (p.measureText(splits[x]) > width) {
            splits[x] = wrap(splits[x], width, p);
            String[] microSplits = splits[x].split(SYSTEM_NEWLINE);
            for (int y = 0; y < microSplits.length - 1; y++)
                microSplits[y] = justify(removeLast(microSplits[y], " "),
                        width, p);
            StringBuilder smb_internal = new StringBuilder();
            for (int z = 0; z < microSplits.length; z++)
                smb_internal.append(microSplits[z]
                        + ((z + 1 < microSplits.length) ? SYSTEM_NEWLINE
                                : ""));
            splits[x] = smb_internal.toString();
        }
    final StringBuilder smb = new StringBuilder();
    for (String cleaned : splits)
        smb.append(cleaned + SYSTEM_NEWLINE);
    tv.setGravity(Gravity.RIGHT);
    tv.setText(smb);
    }

   private static String wrap(String s, float width, Paint p) {

   String[] str = s.split("\\s"); // regex
    StringBuilder smb = new StringBuilder(); // save memory
    smb.append(SYSTEM_NEWLINE);
    for (int x = 0; x < str.length; x++) {
        float length = p.measureText(str[x]);
        String[] pieces = smb.toString().split(SYSTEM_NEWLINE);
        try {
            if (p.measureText(pieces[pieces.length - 1]) + length > width)
                smb.append(SYSTEM_NEWLINE);
        } catch (Exception e) {
        }
        smb.append(str[x] + " ");
    }
    return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
  }

private static String removeLast(String s, String g) {
       if (s.contains(g)) {
           int index = s.lastIndexOf(g);
           int indexEnd = index + g.length();
           if (index == 0)
               return s.substring(1);
          else if (index == s.length() - 1)
               return s.substring(0, index);
          else
              return s.substring(0, index) + s.substring(indexEnd);
    }
    return s;
}

private static String justifyOperation(String s, float width, Paint p) {
    float holder = (float) (COMPLEXITY * Math.random());
    while (s.contains(Float.toString(holder)))
        holder = (float) (COMPLEXITY * Math.random());
        String holder_string = Float.toString(holder);
    float lessThan = width;
    int timeOut = 100;
    int current = 0;
    while (p.measureText(s) < lessThan && current < timeOut) {
        s = s.replaceFirst(" ([^" + holder_string + "])", " "
                + holder_string + "$1");
            lessThan = p.measureText(holder_string) + lessThan
                - p.measureText(" ");
        current++;
    }
    String cleaned = s.replaceAll(holder_string, " ");
    return cleaned;
}

private static String justify(String s, float width, Paint p) {
    while (p.measureText(s) < width) {
        s = justifyOperation(s, width, p);
    }
return s;
}
  }

为了调用我创建的公式,您必须使用以下代码:

 public static final int FinallwidthDp  = 320 ;
 public static final int widthJustify  = 223 ;

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 int widthPixels = metrics.widthPixels;

 float scaleFactor = metrics.density;
 float widthDp = widthPixels / scaleFactor;

 TextView tv = (TextView) findViewById(R.id.textView1);
 ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();

 tv.setText(text);
 TextJustify.run(tv,widthDp / FinallwidthDp * widthJustify , tv.getPaddingLeft(),tv.getPaddingRight() , lp1.leftMargin, lp1.rightMargin);

该算法在各种设备上进行了测试,并且在正常活动(不是对话框)和 wrap-content 宽度中运行良好>TextView,并处理每个填充和边距。如果不适合您,您可以更改 widthJustify 直到看起来适合您,我希望这有用

use the following code:

        public class TextJustify {

        final static String SYSTEM_NEWLINE = "\n";
        final static float COMPLEXITY = 5.12f; // Reducing this will increase
                                     // efficiency but will decrease
                                    // effectiveness
        final static Paint p = new Paint();

        /* @author Mathew Kurian */

   public static void run(final TextView tv, float origWidth, 
          int paddingLeft, int   paddingRight, int marginLeft, int marginRight) {


    origWidth-= paddingRight+marginRight+paddingLeft+marginLeft;
    String s = tv.getText().toString();
    p.setTypeface(tv.getTypeface());
    String[] splits = s.split(SYSTEM_NEWLINE);
    float width = origWidth - 5;
    for (int x = 0; x < splits.length; x++)
        if (p.measureText(splits[x]) > width) {
            splits[x] = wrap(splits[x], width, p);
            String[] microSplits = splits[x].split(SYSTEM_NEWLINE);
            for (int y = 0; y < microSplits.length - 1; y++)
                microSplits[y] = justify(removeLast(microSplits[y], " "),
                        width, p);
            StringBuilder smb_internal = new StringBuilder();
            for (int z = 0; z < microSplits.length; z++)
                smb_internal.append(microSplits[z]
                        + ((z + 1 < microSplits.length) ? SYSTEM_NEWLINE
                                : ""));
            splits[x] = smb_internal.toString();
        }
    final StringBuilder smb = new StringBuilder();
    for (String cleaned : splits)
        smb.append(cleaned + SYSTEM_NEWLINE);
    tv.setGravity(Gravity.RIGHT);
    tv.setText(smb);
    }

   private static String wrap(String s, float width, Paint p) {

   String[] str = s.split("\\s"); // regex
    StringBuilder smb = new StringBuilder(); // save memory
    smb.append(SYSTEM_NEWLINE);
    for (int x = 0; x < str.length; x++) {
        float length = p.measureText(str[x]);
        String[] pieces = smb.toString().split(SYSTEM_NEWLINE);
        try {
            if (p.measureText(pieces[pieces.length - 1]) + length > width)
                smb.append(SYSTEM_NEWLINE);
        } catch (Exception e) {
        }
        smb.append(str[x] + " ");
    }
    return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
  }

private static String removeLast(String s, String g) {
       if (s.contains(g)) {
           int index = s.lastIndexOf(g);
           int indexEnd = index + g.length();
           if (index == 0)
               return s.substring(1);
          else if (index == s.length() - 1)
               return s.substring(0, index);
          else
              return s.substring(0, index) + s.substring(indexEnd);
    }
    return s;
}

private static String justifyOperation(String s, float width, Paint p) {
    float holder = (float) (COMPLEXITY * Math.random());
    while (s.contains(Float.toString(holder)))
        holder = (float) (COMPLEXITY * Math.random());
        String holder_string = Float.toString(holder);
    float lessThan = width;
    int timeOut = 100;
    int current = 0;
    while (p.measureText(s) < lessThan && current < timeOut) {
        s = s.replaceFirst(" ([^" + holder_string + "])", " "
                + holder_string + "$1");
            lessThan = p.measureText(holder_string) + lessThan
                - p.measureText(" ");
        current++;
    }
    String cleaned = s.replaceAll(holder_string, " ");
    return cleaned;
}

private static String justify(String s, float width, Paint p) {
    while (p.measureText(s) < width) {
        s = justifyOperation(s, width, p);
    }
return s;
}
  }

and for calling this I create formula, you must use following code:

 public static final int FinallwidthDp  = 320 ;
 public static final int widthJustify  = 223 ;

 DisplayMetrics metrics = new DisplayMetrics();
 getWindowManager().getDefaultDisplay().getMetrics(metrics);
 int widthPixels = metrics.widthPixels;

 float scaleFactor = metrics.density;
 float widthDp = widthPixels / scaleFactor;

 TextView tv = (TextView) findViewById(R.id.textView1);
 ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();

 tv.setText(text);
 TextJustify.run(tv,widthDp / FinallwidthDp * widthJustify , tv.getPaddingLeft(),tv.getPaddingRight() , lp1.leftMargin, lp1.rightMargin);

this algorithm tested on various device and worked fine in normal activity (not dialog) and wrap-content width for TextView, and worked with every padding and margin.if not good for you, you can change widthJustify until look good to you, I hope this useful

梦断已成空 2024-09-22 14:52:06

XML 布局:声明 WebView 而不是 TextView

<WebView
 android:id="@+id/textContent"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />

Java 代码:将文本数据设置为 WebView

WebView view = (WebView) findViewById(R.id.textContent);
String text;
text = "<html><body><p align=\"justify\">";
text+= "This is the text will be justified when displayed!!!";
text+= "</p></body></html>";
view.loadData(text, "text/html", "utf-8");

这可能会解决您的问题。

XML Layout: declare WebView instead of TextView

<WebView
 android:id="@+id/textContent"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />

Java code: set text data to WebView

WebView view = (WebView) findViewById(R.id.textContent);
String text;
text = "<html><body><p align=\"justify\">";
text+= "This is the text will be justified when displayed!!!";
text+= "</p></body></html>";
view.loadData(text, "text/html", "utf-8");

This may Solve your problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文