2011-03-29 49 views
0

我有一個應用程序與GridView佈局有一個單一的圖像用於測試目的,直到我找出下一步。我已經設置好了一切,但我不知道如何實現一個設計,其中點擊圖像A,B,C,D等時會導致用戶(我)在我指定的網頁上着陸。我需要每個圖像鏈接到不同的位置,我會很感激的幫助落實到我的代碼如下:獲取圖像以鏈接到Android上的GridView中的網頁?

public class ImageAdapter extends BaseAdapter { 
    private Context mContext; 

    public ImageAdapter(Context c) { 
     mContext = c; 
    } 

    public int getCount() { 
     return mThumbIds.length; 
    } 

    public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    // create new ImageView for each item 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 

     if (convertView == null) { 
      imageView = new ImageView(mContext); 
      imageView.setLayoutParams(new GridView.LayoutParams(150, 150)); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
      imageView.setPadding(5, 5, 5, 5); 
     } 

     else { 
      imageView = (ImageView) convertView; 
     } 

     imageView.setImageResource(mThumbIds[position]); 
     return imageView; 
    } 

    // references to images 
    private Integer[] mThumbIds = { 
     R.drawable.A, R.drawable.B, 
     R.drawable.C, R.drawable.D, 
     R.drawable.E, R.drawable.F, 
     R.drawable.G, R.drawable.H, 
    }; 
} 

回答

0

使用getItemId()在適配器(只是返回的位置),選擇您想要的網址要去。就像你有mThumbIds一樣,只需要一個包含匹配URL的並行數組,所以當點擊一個圖像時,它的相應URL可以在同一個索引處輕鬆訪問。

+0

你可以舉一個例子,像google.com嗎?這是我第一次使用網格視圖,我今天才知道它,它仍然在我腦海中迴盪。 – peter 2011-03-29 21:54:40

0

這樣做的「零工作」方法是簡單地啓動一個Intent,它將從OnItemClickListener打開設備瀏覽器中的URL。例如:

//Obtain a reference to the view in your layout somehow...I chose findViewById() 
GridView grid = (GridView)findViewById(R.id.peters_grid); 
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 
     //"position" is the location of the image clicked 
     String url = arrayOfUrls[position]; 
     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setData(Uri.parse(url)); 
     startActivity(intent); 
    } 
}); 

從哪裏獲取字符串數組中每個位置的正確URL。這只是獲得正確URL的一個想法......您可以通過一百萬種不同的方式構建適當的URL,但關鍵是要將它傳遞給Intent然後再觸發它。

這個「小工作」版本將創建一個WebView在這個或另一個Activity,所以你可以加載網頁,並保持在您的應用程序代碼。如果WebView位於第二個Activity中,則最好使用Intent將URL字符串從第一個Activity傳遞到第二個。

希望有助於!

+0

謝謝,你有關於如何製作WebView的好鏈接,我寧願將它全部保留在應用程序中,而不必像我目前那樣啓動瀏覽器。 – peter 2011-03-29 21:56:35

+0

嘗試在SDK文檔中使用WebViews文章,它也有一個示例項目的鏈接:http://developer.android.com/resources/articles/using-webviews.html – Devunwired 2011-03-30 13:06:53

相關問題