簡體   English   中英

如何通過Android Studio使用列表視圖中的鏈接打開網絡瀏覽器?

[英]How Do you open a web browser using links in a listview via android studio?

我正在嘗試創建一個列表視圖,其中列出了三個指向網站的鏈接。 當我從列表視圖中選擇一個項目時,它應該打開Web瀏覽器並將我帶到代碼中鏈接的網站。 我已將三個鏈接放入數組,並且嘗試執行click事件以觸發瀏覽器。

這是我的Java代碼:

package edu.dtcc.bwharto9.intentslab;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
private String[] monthsArray = { "StackOverflow", "Developer.Android", "Javatechig", };


private ListView ListView;
private ArrayAdapter arrayAdapter;

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

    ListView = (ListView) findViewById(R.id.months_list);

    // this-The current activity context.
    // Second param is the resource Id for list layout row item
    // Third param is input array
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, monthsArray);
    ListView.setAdapter(arrayAdapter);

    ListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        public void onItemSelected(AdapterView parentView, View childView,
                                   int position, long id) {
            Intent i = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://stackoverflow.com/"));
            startActivity(i);

            Intent j = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://developer.android.com/"));
            startActivity(j);

            Intent k = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://Javatechig.com/"));
            startActivity(k);
        }
        public void onNothingSelected(AdapterView parentView) {
        }
    });
}

}

如果需要,這是我的XML:

<LinearLayout 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:orientation="vertical">

<ListView
android:id="@+id/months_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:choiceMode="singleChoice">
</ListView>
</LinearLayout>

在此先感謝所有提供幫助的人!

在onItemClickListener上,您應該執行以下操作

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

您應該使用setOnItemClickListener而不是setOnItemSelectedListener

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM