简体   繁体   中英

Clickable listview in fragment

I am trying to create a simple clickable listview in a fragment. (not a listfragment) So when you click a item it goes to a new detailpage about that item.

I got the listview working but I cant seem to figure out how to get the items clickable. I am very new to android programming..

My application is seperated in 4 tabs, this is one of them.

The question is: How do I make items in a listview (in a fragment) clickable?

My fragment class:

  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>

You need to add an OnItemClickListener to your list.

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);
        }

    });

The row you clicked is in arg2.

@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;       

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM