Tuesday, February 12, 2013

Android Clickable TextView

Create a project and have a main activity with following code


MainActivity .java



package com.example.androidhyperlinkbutton;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    TextView textView = (TextView) findViewById(R.id.clickableTextView);
 
    String leading = "This is the clickable ";
    String trailing = "magenta link";
   
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    stringBuilder.append(leading);
    stringBuilder.append(trailing);
    stringBuilder.setSpan(
        new NonUnderlinedClickableSpan() {
            @Override
            public void onClick(View widget) {
            Log.i("ExampleClickableLink", "The link was clicked!");
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://upadhyayjiteshandroid.blogspot.in/"));
            startActivity(browserIntent);
            // do whatever you want here
            }
        },
        leading.length(), leading.length() + trailing.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    textView.setText(stringBuilder);
    textView.setMovementMethod(LinkMovementMethod.getInstance()); 
    textView.setLinkTextColor( Color.GREEN );
}

}


NonUnderlinedClickableSpan .java


package com.example.androidhyperlinkbutton;

import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;

public class NonUnderlinedClickableSpan extends ClickableSpan 
{
@Override
        public void updateDrawState(TextPaint ds) {
           ds.setColor(ds.linkColor);
           ds.setUnderlineText(false); // set to false to remove underline
        }

@Override
public void onClick(View widget) {
// TODO Auto-generated method stub
}
}



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
<TextView  
android:id="@+id/clickableTextView"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:autoLink="all"
 
    />
    
</LinearLayout>




No comments:

Post a Comment