我有AlertDialog
标题应该是
复制" xxx"为...
如果xxx
是一个非常长的字符串,我希望它缩短而不是整个标题:" 对... "部分可见!
举个例子,如果xxx == "A very long text here is being displayed!"
我希望AlertDialog的标题是:
复制"这里有一篇很长的文字... ...#34;为...
怎么做?
答案 0 :(得分:2)
逻辑 =取一个字符串>决定你需要显示的长度>检查你所拥有的字符串的长度>删除不需要的字符以保持您想要的长度>使用您需要添加的其他字符重置新标记>把它当作头!
String headText = "add anything you want here as head";
String newHead;
int maxCharYouWant= 25; // your word limit to display
if(headText.length()>25){
newHead = headText.substring(0, Math.min(headText.length(), 18)); // Get the first N number of words-> here 18
newHead = "\""+newHead+".."+"\""+"to.."; // reset with your format
}else {
newHead = headText; // length is ok no need to change it
}
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.body_layout, null); // for body
AlertDialog.Builder builder = new AlertDialog.Builder(Test.this);
TextView textView = new TextView(Test.this);
textView.setText(newHead);
builder.setCustomTitle(textView);// set your heading
builder.setView(dialogLayout);
builder.show();
编辑:要获得屏幕的字符数,你可以使用这样的方法(我没有在1080的多个设备上测试它,它返回32 ..你可以试试看)
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = (int)((float)size.x/metrics.scaledDensity);
TextView textView = new TextView(Test.this);
int totalCharstoFit= textView.getPaint().breakText(headText, 0, headText.length(), true, width, null);
详细了解breakText