2014-01-11 112 views
0

我有一個擺動視圖以及顯示在我的第一個UI中的4個選項卡。我爲每個Tabs添加了ListView。但OnItemClickListener不適用於ListFragment。我的類從ListFragment擴展並實現OnItemClickListener。我想要做的是,當我從列表中選擇一個項目時,我必須顯示Toast,其中顯示我選擇的項目的名稱。但它不適合我。沒有錯誤發生,但沒有完成任務。任何人都可以幫助我。我給這家完整的代碼如下:在Android ListView中添加ItemListener

import android.os.Bundle; 
import android.support.v4.app.ListFragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

public class TUFragment extends ListFragment implements OnItemClickListener { 

ListView list; 
View rootView; 

final String[] courses = new String[] { "BIM", "BBA", "BBS", "BSc-CSIT", 
     "BSc-IT", "BHM", "BTTM", "MBA", "MBS", "MSc-IT", "MTTM" }; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    rootView = inflater.inflate(R.layout.fragment_tu, container, false); 

    list = (ListView) rootView.findViewById(android.R.id.list); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), 
      android.R.layout.simple_list_item_1, courses); 
    list.setAdapter(adapter); 

    list.setOnItemClickListener(this); 

    return rootView; 
} 

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
    Toast.makeText(this.getActivity(), "You have Selected: " + courses[arg2], 
      Toast.LENGTH_LONG).show(); 
} 
} 

Thankx提前

回答

0

試試這個..

,改變以setListAdapter(adapter);

@Override 
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { 
    String val = ((TextView) v).getText().toString().trim(); 
    Toast.makeText(getActivity(), "You have Selected: " + val, 
      Toast.LENGTH_LONG).show(); 
} 
+0

據我以前不工作。 我也嘗試list.setOnItemClickListener(getActivity()) 它顯示該特定行上的錯誤。 –

+0

@ user3184937檢查我的編輯.. – Hariharan

+0

Thankyou Hariharan jee。現在我可以完成我的其他編碼了。 :) –