有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在中间的AcLtCudio中“椭圆”标题?

我有一个AlertDialog,它的标题应该是

Copying "xxx" to...

如果xxx是一个很长的字符串,我希望它被缩短,而不是整个标题:重要的是“到…”部分是可见的

举个例子,如果我希望AlertDialog的标题为:

Copying "A very long text here is bein..." to...

怎么做


共 (1) 个答案

  1. # 1 楼答案

    逻辑=获取字符串>;确定需要显示的长度>;检查您拥有的字符串长度>;删除不需要的字符以保持所需的长度>;用需要添加的其他字符重置新钉住>;把它当成头

     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