Search code examples
androidtextviewonclicklistener

add read more TextView on another TextView android


I want to add a simply "Read more" / "Read less" Button on an existing TextView combinating another..

I did this:

 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");
                }
            }});

My "announcer_description" TextView is initialize to "Read more".. but this doesn't work.. The only way I found using Read more and Read Less is to nest some many OnClickListener in this OnClickListener..

Someone does have an idea?


Solution

  • Simply "Read More" does not equal "Read more", there is a capitalization difference, so your code is never executed.

    You should set values that don't change, like "Read More", in a String to help prevent these types of mistakes, preferably in strings.xml.

    Create a class wide variable, set it in onCreate():

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

    A simplified 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);
            }
        }
    });
    

    Also notice how I remove the redundant calls to setText(), you don't need to "clear" a previous TextView with setText("").