在片段中使用onItemClick苦苦挣扎

时间:2015-11-30 02:07:57

标签: android android-fragments android-activity android-listview

我已经尝试了许多不同的方法来实现这一点。我有4个可刷卡的选项卡使用片段类,当我扩展片段添加一个列表我无法让onListItemClick工作,我试图使用listfragment但与片段冲突我尝试实现onitemclick并且我尝试了许多toher方法但我总是以错误结束。我在这里得到的错误是onitemclick从未使用过。 有人可以帮忙!!

import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;

public class LeagueOne extends Fragment {


String[] teams = {"Barnsley", "Blackpool", "Bradford City",
        "Burton Albion", "Bury", "Chesterfield", "Colchester United", "Coventry City",
        "Crewe Alexandra", "Doncaster Rovers", "Fleetwood Town", "Gillingham", "Millwall",
        "Oldham Athletic", "Peterborough United", "Port Vale", "Rochdale", "Scunthorpe United",
        "Sheffield United", "Shrewsbury Town", "Southend United", "Swindon Town", "Wallsall", "Wigan Athletic"};

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

    View rootView = inflater.inflate(R.layout.simple_list_item, container, false);
    ListAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, teams);
    ListView lv = (ListView) rootView.findViewById(R.id.list);
    lv.setAdapter(adapter);

    return rootView;
}




protected void onListItemClick (ListView l, View v, int position, long id) {
    if (position == 2) {
        Intent intent = new Intent(getActivity(),BradClass.class);;
        startActivity(intent);

}}}

3 个答案:

答案 0 :(得分:0)

1-您的Fragment必须延长ListFragment才能使用onListItemClick方法。这意味着您必须在片段的布局中定义ListView id @android:id / list

2-然后在您的fragment代码中,您可以使用ListView方法轻松访问getListView()

3-使用setListAdapter(adapter)而不是lv.setAdapter(adapter);

设置其适配器

4-从这一行末尾删除一个半冒号:

Intent intent = new Intent(getActivity(),BradClass.class);;

替代,而不是上述过程,您可以创建自定义ArrayAdapter,传递Activity 上下文到它的构造函数,并在其中设置ListView项的侦听器。

答案 1 :(得分:0)

  

尝试使用以下代码。

 lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
  @Override
            public void onItemClick(AdapterView<?> parent, View view, int     position, long id) {
//your logic for onclick goes here
  }
        });

答案 2 :(得分:0)

实施AdapterView.OnItemClickListener,然后将其设置为ListView

public class LeagueOne extends Fragment implements  AdapterView.OnItemClickListener {

然后将此引用设置为onItemClickListener()

lv.setOnItemClickListener(this)

然后实现onItemClick方法

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      //your logic for onclick goes here
}