2016-04-23 124 views
0

我試圖實現onItemClickListernerListView(請參閱下面的代碼); 當運行它,我得到這個錯誤:如何爲ListView實現onItemClickListerner?

Error:(32, 37) error: incompatible types: List cannot be converted to OnItemClickListener 

List.java

import android.content.Context; 
import android.net.Uri; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.view.ViewGroup; 
import java.util.ArrayList; 


public class List extends Fragment { 
ListView list; 
String[] Winners = { 
    "A", 
    "B", 
    "C", 
    "D", 
    "E" 
}; 
OnSiteSelectedListener SiteListener; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
} 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment_list, container, false); 
    list = (ListView) v.findViewById(R.id.fragment1); 
    list.setAdapter(new ArrayAdapter <String> (getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, Winners)); 
    list.setOnItemClickListener(this); 
    return v; 
} 

public void onItemClick(AdapterView adapterView, View view, int position, long l) { 
    SiteListener.onSiteSelected(position); 
} 
public interface OnSiteSelectedListener { 
    public void onSiteSelected(int i); 
} 

public void setRefrence(OnSiteSelectedListener siteListener) { 
    this.SiteListener = siteListener; 
} 
} 
+0

你的類必須實現' –

回答

0

List類需求執行OnItemClickListener。你已經實現了onItemClick()方法,所以你只需要在接口添加到類聲明:

public class List extends Fragment implements AdapterView.OnItemClickListener { 
+1

AdapterView.OnItemClickListener'它解決。非常感謝, – Albert

0

您需要執行onItemClickListernerListView這樣

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

     // HANDLE WHATEVER YOU WANNA DO WITH LISTVIEW CLICKS HERE 
     SiteListener.onSiteSelected(position); 

     } 
0

您可以在一流的呼叫setOnItemClickListener沒有工具。所以你可以用以下兩種方式解決它。

public class List extends Fragment implements AdapterView.OnItemClickListener 

OR

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

      String item = ((TextView)view).getText().toString(); 

      Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show(); 

     } 
    });