ブラウザを起動するボタンを作る
今回はボタンをクリックするとブラウザが起動して「Yahoo!」サイトを表示するサンプルを作ります。
動作の流れは、Uriに「Yahoo!」のアドレスをセットし、UriをセットしたIntent(ACTION_VIEW)を作成して、最後にそのIntentをstartActivityで開始します。
手続きが少々面倒ですが知っておいて損はありませんので、このサンプルで流れをしっかり覚えてしまいましょう。
サンプルコード①(MainActivity.java)
詳しい説明はコード内のコメントを参考にしてください。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//レイアウトファイルをセット
setContentView(R.layout.activity_main);
//アクションバーを取得
ActionBar actionBar = getActionBar();
//アクションバーを隠す
actionBar.hide();
//レイアウトファイルのボタンを取得
Button button = (Button)findViewById(R.id.button);
//取得したボタンにクリックイベントをセット
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//ブラウザで開きたいサイトをuriにセット
Uri uri = Uri.parse("http://yahoo.co.jp");
//uriを開くインテントを作成
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//uriを開くアクティビティをスタートします
startActivity(intent);
}
});
}
}
サンプルコード②(activity_main.xml)
レイアウトファイルは中央にボタンがあるだけの単純な構造です。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yahoo!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
実行結果
中央のボタンをクリックすると…
「Yahoo!」のウェブサイトが表示されました。
END