如何在 android 中仅展开 textview

how to expand only textview in android

我正在尝试在 android 中扩展 textview,我有一些包含大量内容的 textview,我的要求是只显示来自大量内容的两行并完成 (...)。如果我点击它,我的全部内容将不得不显示。如何 做到这一点。你能帮帮我吗?

public class MainActivity extends ActionBarActivity {       
TextView t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);  
   t1 = (TextView) findViewById(R.id.text);
   String str = "If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying. This allows animations for those drawables to be scheduled." +
                "I made the expandable list view acc to your tutorial but what i have to do if I want to populate Expandable List View with values from database?Means what changes I have to do in ";
    t1.setText(str);                               
    t1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        t1.setMaxLines(Integer.MAX_VALUE);
    }
 });
}
}

您可以在您的布局中将 textview 的 android:maxLines 属性 默认设置为 2 xml..

在将文本设置到文本视图 (t1) 后的 onCreate() 函数中。
添加以下内容

 boolean isTextViewClicked = false;

t1.setOnClickListener(new OnClickListener() {
    if(isTextViewClicked){
      //This will shrink textview to 2 lines if it is expanded.
       t1.setmaxLines(2);
       isTextViewClicked = false;
    } else {
       //This will expand the textview if it is of 2 lines
       t1.setMaxLines(Integer.MAX_VALUE);
       isTextViewClicked = true;
    }
});

这将根据内容扩展文本视图

我在 medium article 中描述了最佳和优化方法。

您需要做的是 运行 TextView.post{} 函数中的以下函数:

private fun TextView.setCaption(senderName: String, caption: String) {
    text = getFullCaption(senderName, caption)

    if (lineCount > DEFAULT_LINES) {
        val lastCharShown = layout.getLineVisibleEnd(DEFAULT_LINES - 1)
        maxLines = DEFAULT_LINES
        val moreString = context.getString(R.string.read_more)
        val suffix = " $moreString"
        // 3 is a "magic number" but it's just basically the length of the ellipsis we're going to insert
        val actionDisplayText = context.getString(R.string.more_dots) + suffix

        text = SpannableStringBuilder()
            .bold { append(senderName) }
            .append("  ")
            .append(
                caption.substring(
                    0,
                    lastCharShown - suffix.length - 3 - moreString.length - senderName.length
                )
            )
            .color(Color.GRAY) { append(actionDisplayText) }
    }
}

在TextView的扩展函数中调用setCapton函数并设置点击监听让它展开,是你拥有一个可展开的TextView的最后一步:

private fun TextView.setExpandableText(senderName: String, caption: String) {
    post {
        setCaption(senderName, caption)
        setOnClickListener {
            let {
                it.maxLines = MAX_LINES
                it.text = getFullCaption(senderName, caption)
            }
        }
    }
}