为滑动菜单片段中的列表视图添加一个项目单击列表器



我的Android应用程序中有一个带有片段和列表视图的滑动菜单。我想为此片段添加项目单击侦听器。这是我用于片段的代码:

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LeftMenuFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.leftmenu, container, false);
  }
}

这是菜单布局的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#2C323F" >
<TableLayout
    android:id="@+id/tableLayout1"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="0dp" 
    android:background="@drawable/blue_bg">
</TableLayout>
<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/searchView1"
    android:layout_centerHorizontal="true" 
    android:entries="@array/menu_array">
</ListView>

这里的menu_array是一个字符串资源。我想为片段中的列表视图添加项目单击列表器。如何做到这一点 这对我来说很复杂。

提前谢谢你!

你可以在onCreateView中试试这个:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.leftmenu, container, false);
    ListView list = (ListView) view.findViewById(R.id. listView1);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
        // do things with the clicked item
    }
    });
    return view;
  }
}

或者,如果 onItemClick 方法需要活动中的任何内容才能正常工作,则可以保留对列表的引用,并在片段的 onActivityCreated 中设置 OnItemClickListener。

我希望这对;)有所帮助

最新更新