C/C++プログラマの管理者が, Androidプログラムにチャレンジ. AndroidプログラミングのTipsをメモっていく予定です.

URLやメールアドレスなどの文字列をリンクに変換する方法は2通りある.
には, テキストビュー(TextView)クラスのsetAutoLinkMaskメソッドをしようする.



XMLファイルにより定義

  • res/values/strings.xml
    • リンクに変換する文字列を定義する.
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">文字列をリンクに変換する</string>
  <string name="text_label">Link : http://www.yahoo.co.jp</string>
</resources>
  • res/layout/main.xml
    • "android:autoLink"属性に, 文字列の何をリンクに変換するか設定する.
引数
対象
all下記すべて
emalメールアドレス
mapマップアドレス
phone電話番号
webURL
    • "@string/text_label"で表示する文字列を指定する.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/layout_id"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:id="@+id/textview_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:autoLink="all"
    android:text="@string/text_label"
  />
</LinearLayout>

コードにより定義

  • TextView01.java
    • findViewByIdメソッドで, TextViewのインスタンスを取得する.
    • TextView#setAutoLinkMaskメソッドで, 文字列の何をリンクに変換するか設定する.
引数
対象
Linkify.ALL下記すべて
Linkify.EMAIL_ADDRESSメールアドレス
Linkify.MAP_ADDRESSマップアドレス
Linkify.PHONE_NUMBERS電話番号
Linkify.WEB_URLSURL
    • TextView#setTextメソッドで, 変換する文字列を設定する.
   注) 文字列をsetAutoLinkMaskより先に設定すると, リンクに変換されない.
package com.moonlight_aska.android.textview01;
import android.app.Activity;
import android.os.Bundle;
import android.text.util.Linkify;
import android.widget.TextView;

public class TextView01 extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView text = (TextView)findViewById(R.id.textview_id);
    // リンクに変換するものをMask値で決める.
    text.setAutoLinkMask(Linkify.ALL);
    text.setText("Link : http://www.yahoo.co.jp");
  }
}



コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



管理人/副管理人のみ編集できます