Pages

Wednesday, September 21, 2016

Android Example- Match Filter (create keyword to serch directly into website)



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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello_world"
        android:id="@+id/textview1" />

</RelativeLayout>

MainActivity.java
package in.kantapp.example35;

import java.util.regex.Pattern;

import android.os.Bundle;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.text.util.Linkify;
import android.text.util.Linkify.MatchFilter;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{

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

        MatchFilter myMatchFilter = new MatchFilter()
        {
            @Override
            public boolean acceptMatch(CharSequence cs, int start, int end)
            {
                return ((start == 0 || cs.charAt(start - 1) == '!') && !(cs
                        .charAt(start) == 'p'));
            }
        };

        TextView myCustomLink2 = (TextView) findViewById(R.id.textview1);
        Pattern pattern2 = Pattern.compile("[a-zA-Z]+");
        myCustomLink2
                .setText("press one of these words to search it on google:"
                        + " !Google !Linkify !kantapp.in");
        Linkify.addLinks(myCustomLink2, pattern2,
                "http://www.google.ie/search?q=", myMatchFilter, null);

    }



}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.kantapp.example35">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

No comments:

Post a Comment