How to make textview's text clickable to activity
Sometimes, in android developement, we want to make our textview’s text clickable, that is, when user click a link in textview’s content, user would open an activity,here are the code examples:
in res/values/strings.xml, there is a string like this:
<string name="guide">
<![CDATA[
* You can click <a href="RegisterActivity://ra">here</a> to register
]]>
</string>
Here we want the user can click ‘here’ to open an activity named RegisterActivity
then, in AndroidManifest.xml add an intent filter to RegisterActivity:
<activity
android:name=".RegisterActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name=".RegisterActivity"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<data android:scheme="RegisterActivity" />
</intent-filter>
</activity>
the most important part is the second intent-filter, which includes “android.intent.action.VIEW” action and the data settings. Here ,we set the schema to “RegisterActivity”,then in your strings.xml ,you just set the link as this:
<a href="RegisterActivity://ra">here</a>
the ra is the path of the url, you can pass some parameters to the activity.
in the layout, you have a textview like this:
<TextView
android:id="@+id/tvGuide"
style="@style/NormalText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
at last, you change the code of the textview,add init code like this:
TextView tvGuideDesc = (TextView)this.findViewById(R.id.tvGuide);
if(tvGuideDesc!=null) {
tvGuideDesc.setText(Html.fromHtml(String.format(
this.getString(R.string.guide))));
tvGuideDesc.setMovementMethod(LinkMovementMethod.getInstance()); //this line is important
}
The most import line of the upper code is:
tvGuideDesc.setMovementMethod(LinkMovementMethod.getInstance()); //this line is important
the LinkMovementMethod make your text link clickable.
Then , you can test it.
You can find detail android documents about the data intent-filter here: