如何为ListView实现onItemClickListerner?

时间:2016-04-23 06:29:41

标签: java android android-fragments onitemclicklistener

我正在尝试为onItemClickListerner实施ListView(请参阅下面的代码); 运行时,我收到此错误:

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;
 }
}

3 个答案:

答案 0 :(得分:0)

您需要为此onItemClickListerner实施ListView

 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);

        }

答案 1 :(得分:0)

List类需要实现OnItemClickListener。您已经实现了onItemClick()方法,因此您只需要将接口添加到类声明中:

public class List extends Fragment implements AdapterView.OnItemClickListener {

答案 2 :(得分: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();

        }
    });