簡體   English   中英

點擊偵聽器上的Android網格視圖獲取選定項

[英]Android grid view on click listener get selected item

我正在嘗試從Android開發中的網格視圖中獲取選定的項目。 這是我用來填充網格視圖的drawable列表:

private static Integer[] iconlist = {
        R.drawable.food_icon, R.drawable.transport_icon, R.drawable.entertainment_icon,
        R.drawable.bill_icon, R.drawable.others_icon, R.drawable.salary_icon,
        R.drawable.investment_icon, R.drawable.bonus_icon, R.drawable.medication_icon,
        R.drawable.drinks_icon, R.drawable.car_icon, R.drawable.mask_icon,
        R.drawable.shopping_icon, R.drawable.lottery_icon, R.drawable.pet_icon,
        R.drawable.movie_icon, R.drawable.plant_icon, R.drawable.paint_icon,
};

以及點擊偵聽器上的gridview:

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                                View v, int position, long id) {

            Toast.makeText(getActivity(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
            int selected = position + 1;
            for(int i = 0; i < iconlist.length; i++){
                if(iconlist[i] == selected){

                }
            }
        }
    });

我根據點擊次數獲得了正確的整數位置。 我想做的是基於所選的drawable,我想提取出字符串。

例如,當單擊傳輸圖標時,我試圖從“ R.drawable.transport_icon”中獲取“ transport_icon”字符串並將其存儲為字符串。 但是,我不確定該怎么做。

有任何想法嗎?

首先從整數數組(ID)定義一個可繪制對象

Drawable drawable = context.getResources().getDrawable(iconlist[n]);

你可以得到這樣的資源名稱

String name = context.getResources().getResourceEntryName(ID);

此方法應返回您需要的內容。

您可以按照以下方式嘗試:

Context.getResources().getResourceEntryName(R.drawable.transport_icon)

要么

Context.getResources().getResourceName(R.drawable.transport_icon)

參考: https : //developer.android.com/reference/android/content/res/Resources.html#getResourceEntryName(int)

暫無
暫無

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

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