簡體   English   中英

如何從ListView中提取所選項?

[英]How to extract selected item from ListView?

我有一個只能選擇一個項目的Listview。 當該項獲得點擊時,它會運行AsyncTask。 在onPostExecute()中,彈出一個AlertBox對話框。 但我要做的是讓所選項目顯示在alertBox內部,我已經嘗試了我能想到的一切。 任何幫助將不勝感激,並提前感謝您。

這是我的ListView設置。

    Public class MyClass extends Activity
    {
    list.setAdapter(new ArrayAdapter<String>(this, R.layout.vacation_tracks, vacation_menu));

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

            for(int i = 0; i<vacation_menu.length; i++)
            {

                if(((TextView) view).getText().equals(vacation_menu[i]))
                {

                    Sizes work = new Sizes();
                    work.execute(tempLink);
            } 
        }
    }); 
   }

這是我的AsyncTask類。 我的目標是在onPostExecute()的Title()方法中獲取所選項(或TextView中與所選項關聯的文本)。

    Private Class Sizes extends AsyncTask<URL, Void, Float>
    {
        protected float doInBackground(URL...urls)
        {
             //gets url.getContentLength();
        }

        protected void onPostExecute(Float result)
        {
            AlertDialog.Builder alertbox = new AlertDialog.Builder(Vacation.this);
            alertbox.setMessage( Title( ITEM FROM LISTVIEW     ) );
            alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface arg0, int arg1) 
                {

                }
            });
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface arg0, int arg1)
                {

                }
            });
            alertbox.show();

    } 


}

再次感謝您的幫助!

您可以使用onItemClick偵聽器的position參數從數據源中獲取單擊的項目,然后將此數據傳遞給AsyncTask對象,並在那里使用它(在Alert框中顯示)

如果您的任務是在Activity的范圍內定義的,則可以使用final關鍵字:

final String alertBoxTitle = vacation_menu[i];
Sizes work = new Sizes();
work.execute(tempLink);

alertbox.setMessage(alertBoxTitle);

如果您的任務不在您的活動范圍內,您可以將標題作為參數或通過設置者傳遞。 在你的情況下,塞特似乎更容易。

在你的任務中:

String title;

public void setTitle(String title) {
  this.title = title;
}

protected void onPostExecute(Float result) {
  AlertDialog.Builder alertbox = new AlertDialog.Builder(Vacation.this);
  alertbox.setMessage(title);
  // ...
}

像這樣使用它:

Sizes work = new Sizes();
work.setTitle(vacation_menu[i]);
work.execute(tempLink);

如果AsynTask在您的活動內部,那么您可以訪問listview成員並獲取所選項目。 呼叫

mListView.getSelectedItem(); // returns the object associated with this item.

要么

您可以通過參數將對象傳遞給AsyncTask 將標題字符串傳遞給Size構造函數。 像這樣

Sizes work = new Sizes(mListView.getSelectedItem().getTitle());
work.execute(tempLink); 

如果你只是想創建一個警告對話框,你不需要AsyncTask ..只需在你的onListItemClick中添加代碼getSelectedItem並從中創建一個警告..

暫無
暫無

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

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