0

我正在开发一个应用程序,它使用ActionBar选项卡来显示ListFragment的选项列表。 list(和ListFragment)显示没有问题,但ListView的setOnItemClickListener似乎不起作用,因为单击列表中的项目时没有任何反应。下面是该ListFragment类的代码:ListView setOnItemClickListener in ListFragment not working

package XXX.XXX; 

public class AboutFrag extends SherlockListFragment 
{ 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
    { 
      View view = inflater.inflate(R.layout.aboutfrag, container, false); 

      ListView lv = (ListView) view.findViewById(android.R.id.list); 

      String[] items = new String[] {"About 1", "About 2", "About 3"}; 

      lv.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_item, items)); 

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

        switch (position) 
        { 
         case 0: 
          Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com")); 
          startActivityForResult(browserIntent, 0); 
          break; 

         case 1: 
          Intent browserIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("http://wikipedia.org")); 
          startActivityForResult(browserIntent2, 0); 
          break; 

         case 2: 
          Intent browserIntent3 = new Intent(Intent.ACTION_VIEW, Uri.parse("http:/android.com"); 
          startActivityForResult(browserIntent3, 0); 
          break; 
        }   
       } 
       }); 

      return view; 
    }  
} 

我猜想这是行不通的,因为类返回视图对象,所以FragmentActivity不能运行监听器的代码,所以没有人知道如何使这个工作?顺便说一下,我使用ActionBarSherlock。提前致谢!!!

回答

6

您也可以覆盖从SherlockListFragment继承的onListItemClick方法。

如下:

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

    switch (position) 
        { 
         case 0: 
          Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com")); 
          startActivityForResult(browserIntent, 0); 
          break; 

         case 1: 
          Intent browserIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse("http://wikipedia.org")); 
          startActivityForResult(browserIntent2, 0); 
          break; 

         case 2: 
          Intent browserIntent3 = new Intent(Intent.ACTION_VIEW, Uri.parse("http:/android.com"); 
          startActivityForResult(browserIntent3, 0); 
          break; 
        } 

} 
+0

马尔科您好,感谢您的答复!它工作得很好! – siddarthkaki

+0

这帮了我。谢谢。 – ernell