TextView android:ellipsize =“end”问题

时间:2012-03-26 11:04:27

标签: android textview

在我的应用程序中,我ellipsizeTextView,因此如果文字过大,最后会使用...显示android:ellipsize="end"

egText ABCDEFGHIJKLMNOPQRSTUVWXYZ显示为ABCDEFGHIJ...。但是当文字较小时,例如ABCDEF,它仍会在结尾显示...,使文字看起来像AB...。我无法修复textview的宽度,因为在其他地方使用相同的textview有一些不同的宽度要求。我应该怎么做才能使它工作,只有当文本足够大时才显示...

2 个答案:

答案 0 :(得分:11)

//在你的textview中

还添加以下属性

android:maxEms="8"
android:singleLine="true"

注意:您可以将ems大小调整为您想要显示的字符数。

答案 1 :(得分:1)

 txtvw.setText("The Indian economy is the world's eleventh-largest by nominal GDP and third-largest by purchasing power parity (PPP). " +
                "      Following market-based economic reforms in 1991, India became one of the fastest-growing major economies; " +
                "      it is considered a newly industrialised country. However, it continues to face the challenges of poverty, illiteracy, corruption, malnutrition, and inadequate public healthcare. " +
                "      A nuclear weapons state and a regional power, it has the third-largest standing army in the world and ranks ninth in military expenditure among nations." +
                "      India is a federal constitutional republic governed under a parliamentary system consisting of 28 states and 7 union territories. " +
                "      India is a pluralistic, multilingual, and multiethnic society. " +
                "      It is also home to a diversity of wildlife in a variety of protected habitats.");
        ViewTreeObserver vto = txtvw.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                ViewTreeObserver obs = txtvw.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if(txtvw.getLineCount() > 1){

                    int lineEndIndex = txtvw.getLayout().getLineEnd(1);
                    String text = txtvw.getText().subSequence(0, lineEndIndex-3)+"...";
                    txtvw.setText(text);

                }

            }
        });