user1641906
user1641906

Reputation: 117

How to display TextView using ToggleButton in Android

I have a toggleButton with a textView. The idea is that when the "plus" image on the togglebutton is clicked, it will reveal the full textView.

At the moment, I can display Toasts correctly, as below:

ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
            toggleButton.setOnClickListener(new View.OnClickListener() {
              public void onClick(View v) {
                if (((ToggleButton) v).isChecked())
                     DisplayToast("Toggle button is On");
                else
                  DisplayToast("Toggle button is Off");
              }


            });
          }
      private void DisplayToast(String msg) {
            Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
          }

BUT I WANT TO INCORPORATE:

TextView tv = (TextView) Design.this.findViewById(R.id.textView2);
                    tv.setVisibility(View.VISIBLE);

After the "if" statement. But Android doesn't like it. How do I add the above statement (with a "else" showing same statement, but View.GONE ??

Upvotes: 0

Views: 1411

Answers (1)

wbk727
wbk727

Reputation: 8408

Try this:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:id="@+id/textView" />

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New ToggleButton"
        android:id="@+id/toggleBtn"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView)findViewById(R.id.textView);

    ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggleBtn);
    toggleButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (((ToggleButton) v).isChecked())
                tv.setVisibility(View.VISIBLE);
            else
                tv.setVisibility(View.GONE);
        }


    });
}

Upvotes: 2

Related Questions