ListFragment中的ListView单击项目

时间:2013-12-21 22:00:58

标签: android android-listfragment

我在我的应用程序中有一个简单的ListFragment来显示像Strings这样的静态数据。我需要使用Single Choice使列表项可单击。这是我到目前为止所尝试的。我可以看到列表项,但我无法从单击列表项中获取任何日志。 这段代码出了什么问题?

public class SettingsTab extends ListFragment implements OnItemClickListener{
String[] numbers={"one","two","three","four"};
ListView list ;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Settings tab", "Fragment Created (onCreate)");
    }
 @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("Settings tab", "Fragment Created (onActivityCreate)");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.settingsfragment, container, false);
        list = (ListView)v.findViewById(android.R.id.list);
        list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        list.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.listitemlayout,
                R.id.listitemUniName, names));
        list.setOnItemClickListener(this);
        Log.d("Settings tab", "Fragment Created (onCreateView)");
        return v;
    }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        Toast.makeText(getActivity().getBaseContext(), "Item clicked: " + arg2, Toast.LENGTH_LONG).show();
        Log.d("settings", "click worked");
    }

2 个答案:

答案 0 :(得分:2)

ListFragment已经是一个侦听器,因此不要设置OnItemClickListener,而是覆盖此方法:http://developer.android.com/reference/android/app/ListFragment.html#onListItemClick(android.widget.ListView,android.view.View,int,long)。

答案 1 :(得分:1)

@Jukka Raanamo是对的,这对我有帮助,你可以摆脱OnItemClickListener和方法onItemClick()。然后覆盖onListItemClick()

例如:

    @Override
    public void onListItemClick(ListView l, View v, int position, long id)
    {
       super.onListItemClick(l, v, position, id);
       // Do whatever you need to do here.
       Toast.makeText(getActivity().getBaseContext(), "Item clicked: " + arg2, Toast.LENGTH_LONG).show();
       Log.d("settings", "click worked");
    }

谢谢@Jukka Raanamo