Android listview within a fragment
Solution 1
The biggest issue is mis-matched variable names. You call out lv1
as a class member and set a list adatper against that, but you use listView
to find the view. One of those needs to change.
The following change ought to help out:
lv1 = (ListView) view.findViewById(R.id.listView1);
Solution 2
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab3, container, false);
listView = (ListView) view.findViewById(R.id.ListView1);
listView.setAdapter(files);
Try doing this in your code
Solution 3
Try extending ListFragment
instead of Fragment
. This will give you the functionality like onListItemClick
for your list. You can also use getListView()
when extending ListFragment
. Then in your xml you can use the android list
id:
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Then in your onActivityCreated() you can set your list adapter with setListAdapter without having to use findViewById
progdoc
Updated on June 04, 2022Comments
-
progdoc almost 2 years
I have an app with 2 tabs. Each tab has it's respective fragment. On one of the tabs I would need to place a listview in order to receive data from stored arrays and place them as a list.
This is my code till now:
public class Frag3 extends Fragment{ ListView lv1; ProgressDialog ShowProgress; public ArrayList<Post> PostList = new ArrayList<Post>(); TextView tv1; Button button1; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } View view = inflater.inflate(R.layout.tab3, container, false); //View tv = view.findViewById(R.id.textView1); View listView = view.findViewById(R.id.listView1); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter<String> files = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values); lv1.setAdapter(files); return view; } }
I've tried various options from different web references however none of them seemed to work. Can someone kindly guide me towards a way forward as I'm lost right now and can't seem to understand the next steps.
-
Joakim Engstrom almost 11 yearsIf you override the onCreateView in the ListFragment, this, seems by far, the best way to go if you create the layout in xml.