片段中的可点击列表视图

时间:2013-12-01 14:16:34

标签: java android xml eclipse

我正在尝试在片段中创建一个简单的可点击列表视图。 (不是listfragment) 因此,当您点击某个项目时,它会转到有关该项目的新详细信息页面。

我得到了listview,但我似乎无法弄清楚如何让这些项目可以点击。我是android编程的新手..

我的应用程序分为4个选项卡,这是其中之一。

问题是:如何使listview(片段中)的项目可点击?

我的片段类:

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

  public class BiblioFragment extends Fragment {

final String[] items = new String[] { "Android", "iPhone", "WindowsMobile",
        "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
   "Linux", "OS/2" };

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

    View view = inflater.inflate(R.layout.fragment_biblio, container, false);

    ListView list = (ListView)view.findViewById(R.id.listView1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
    list.setAdapter(adapter);

    return view;       
}

}

XML

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
</ListView>

2 个答案:

答案 0 :(得分:3)

您需要在列表中添加OnItemClickListener。

list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
           Log.v("TAG", "CLICKED row number: " + arg2);
        }

    });

您点击的行位于arg2。

答案 1 :(得分:2)

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

View view = inflater.inflate(R.layout.fragment_biblio, container, false);

ListView list = (ListView)view.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);

list.setOnItemClickListener(new OnItemClickListener() 
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        {
        Intent intent = new Intent(MainActivity.this, nextActivity.class);
        startActivity(intent);
        }
    });

return view;       

}