android 在另一个TextView安卓系统上添加阅读更多TextView

rn0zuynd  于 2022-12-21  发布在  Android
关注(0)|答案(2)|浏览(178)

我想添加一个简单的“阅读更多”/“阅读更少”按钮上现有的TextView组合另一个..
我是这么做的

this.announcer_description = (TextView) findViewById(R.id.announcer_description);
    this.readmore = (TextView) findViewById(R.id.readmore);
    this.readmore.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (readmore.getText().equals("Read More"))
                {
                    announcer_description.setText("");
                    announcer_description.setText(currentAnnouncer.getDescription_fr());
                    readmore.setText("");
                    readmore.append("Read less");
                }
                else if (readmore.getText().equals("Read less"))
                {
                    announcer_description.setText("");
                    announcer_description.setText(shortDesc);
                    readmore.setText("");
                    readmore.append("Read more");
                }
            }});

我的“announcer_description”文本视图被初始化为“Read more”..但这不起作用..我发现使用Read more和Read Less的唯一方法是在这个OnClickListener中嵌套一些OnClickListener..
有人有主意了吗?

dced5bon

dced5bon1#

简单地说,"Read More"不等于"Read more",存在大小写差异,因此您的代码永远不会执行。
您应该在String中设置不变的值,如"Read More",以帮助防止这类错误,最好是在strings.xml中。
创建一个类范围变量,在onCreate()中设置它:

String readMoreString;
...
readMoreString = getResources().getText(R.string.read_more);

简化的OnClickListener:

this.readmore.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        if (readmore.getText().toString().equals(readMoreString))
        {
            announcer_description.setText(currentAnnouncer.getDescription_fr());
            readmore.setText(readLessString);
        }
        else 
        {
            announcer_description.setText(shortDesc);
            readmore.setText(readMoreString);
        }
    }
});

还要注意我是如何删除对setText()的冗余调用的,您不需要使用setText("")“清除”以前的TextView。

zqdjd7g9

zqdjd7g92#

我需要使用这个在回收站的看法和面临的问题,这个图书馆解决了我的问题。
https://github.com/giangpham96/ExpandableTextView

相关问题