user1641906
user1641906

Reputation: 117

How to create dropdown text within a TextView - Android

I'd like to create a TextView in Android which, when clicked on, shows the rest of the text ie similar to the hide/show of import statements, where clicking on the minus/plus shows/hides the rest of the import statements. I want this so as to save space on the screen! I've seen examples with Textview and Spinner - but these are creating lists to choose items from - I just want a simple hide/show, with a title showing, and an arrow or minus/plus sign to hide/show the full document.

Upvotes: 0

Views: 10234

Answers (3)

Fartab
Fartab

Reputation: 5503

I think you need something like this:

XML:

<LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/expandableTextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <ImageButton
            android:id="@+id/expandBtn"
            android:src="@drawable/plusIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        </LinearLayout>


Code:

    final int MIN_CHARS = 10;
    String fullText;
    boolean isExpanded;

    TextView textView = (TextView) findViewById(R.id.expandableTextView);
    ImageButton imageButton = (ImageButton) findViewById(R.id.expandBtn);

    fullText = textView.getText().toString();
    textView.setText(fullText.substring(0,MIN_CHARS));
    imageButton.setImageResource(R.drawable.plusIcon);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            isExpanded = ! isExpanded;
            imageButton.setImageResource(isExpanded?R.drawable.minusIcon:R.drawable.plusIcon);
            textView.setText(isExpanded?fullText:fullText.substring(0,MIN_CHARS));
        }
    });

Upvotes: 0

GordonW
GordonW

Reputation: 1120

Create a custom listview adapter, within the view method add reference/declare your plus/minus buttons, within the onClick statement (inside adapter) add methods for the plus and minus which will switch layouts depending on which is 'clicked' i.e. when plus clicked execute alternative layout, when minus selected execute standard layout. Theres plenty online resources on creating custom adapters if your unsure..

Upvotes: 0

Anitha Manikandan
Anitha Manikandan

Reputation: 1170

In your case, Instead of creating custom textview, just create a custom layout, which has two textviews in it. You can write methods to set/get texts and show/hide any text views present in the layout.

Upvotes: 0

Related Questions