对于Fragment类型,未定义onListItemClick(ListView,View,int,long)方法

时间:2014-04-22 10:08:28

标签: android android-fragments

我收到方法onListItemClick(ListView, View, int, long) is undefined for the type Fragment错误:

FragmentC.java:

package com.example.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

public class FragmentC extends Fragment{

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

        TextView mtext  = new TextView(getActivity());
        mtext.setText("Fragment C added. \n Click back button to go previous state");
        mtext.setBackgroundColor(Color.MAGENTA);
        mtext.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
     LayoutParams.MATCH_PARENT));

        return mtext;
    }
    public void onListItemClick(ListView l, View v, int position, long id) {

        super.onListItemClick(l, v, position, id);  <---Error occurred here

        if(position == 2)
        {
        Fragment newFrag = new FragmentC();
        FragmentTransaction trans = getFragmentManager().beginTransaction();
        trans.add(R.id.fragment_container, newFrag);
        trans.addToBackStack(null);
        trans.commit();
    }
    else
    {

    }
    }
    }

任何人都知道如何解决这些问题。谢谢。

2 个答案:

答案 0 :(得分:3)

public class FragmentC extends Fragment{片段没有那种方法。

ListFragment有方法。因此,您要ListFragment而不是Fragment

http://developer.android.com/reference/android/app/ListFragment.html

但是在你的片段中你有一个TextView。为什么在不延长onListItemClick时甚至需要ListFragment?我也没有看到ListView。你所拥有的只是一个TextView而你没有提供你实际需要的其他信息。

答案 1 :(得分:0)

您可能希望从ListFragment check this

扩展
public static class FragmentC  extends ListFragment {

   // ...
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }
}

您还需要@override关键字。