Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find listview in 'fragment'

I am having a fragment that send request to server and download json , then parse it into a listview , somehow i can't reach the view properly.below is some part of my apps , this is my first touch on listview with fragment , for some reason i only allow to use Fragment so i choose 'setAdapter' instead of 'setListAdapter' to be my adapter

myfragment.java

 public class gallery extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View myFragmentView = inflater.inflate(R.layout.tab_frag2_layout,
                    container, false);
            return myFragmentView;
        }

    public void onActivityCreated(Bundle savedInstanceState) {
    .........
    .........
    .........
    setAdapter(colorAdapter);

    }

layout.tab_frag2_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:background="#ffffff">

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/list_padding"
    android:paddingRight="@dimen/list_padding"
    android:tag="listf" />

</LinearLayout>

My expectation is using

MyListView = (ListView)myFragmentView.findViewById(R.id.list);

to get my view , but it doesn't work that way... Now I just want to get my listview and apply

MyListView.setAdapter(colorAdapter) to it

any help would be appreciated, thanks

like image 622
Leon Armstrong Avatar asked Dec 27 '22 10:12

Leon Armstrong


2 Answers

Option1: Since your fragment layout consists of just a simple ListView. Consider using

public class gallery extends ListFragment

Then you can use this code to get your listview.

myFragmentView.getListView()

Option2: As Nickolaus mentioned, you need a custom id if you want to use findViewById.

android:id="@+id/listview1"

like image 95
Calvin Avatar answered Jan 08 '23 11:01

Calvin


If you don't want to use a ListFragment, you need to add a custom id (android:id="@+id/custom_id") then you can use findViewById to find the ListView

like image 21
Nickolaus Avatar answered Jan 08 '23 09:01

Nickolaus