Search code examples
androidandroid-switch

How can I add a link to the text of a Switch widget?


I am trying to make an "Accept terms and conditions" switch. I was able to add the link into the switch but the problem is that the link is also on the switch button so each time I press the button to accept the terms and conditions it carry me to the webpage.

I would like that only the text that is selected as link, will be the link.

Here is the code that I have now:

On strings.xml:

<string name="terms">Accept<a href="http://www.google.es">terms & conditions</a>.</string>

On register.xml:

<Switch
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/terms"
     android:id="@+id/registerSwitch"/>

On Register.class:

Switch terms = (Switch) findViewById(R.id.registerSwitch);
terms.setMovementMethod(LinkMovementMethod.getInstance());

How can I make that only the text "terms & conditions" will be the link and not the switch button?


Solution

  • Why don't you display the text separately as a TextView and setOnClickListener on the TextView to open your link. Some what like this:

             <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
    
                <Switch
                    android:id="@+id/your_switch"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                <TextView
                    android:id="@+id/terms_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Accept terms &amp; conditions" />
    
            </LinearLayout>
    

    In Activity

    TextView termsText = (TextView)findViewById(R.id.terms_text);
        termsText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.yoururl.com"));
                startActivity(browserIntent);
            }
        });