I am using ListView with ArrayAdapter and trying to add fragments to all rows of the ListView. However, the app does not work correctly: only one row on the screen showed with the added fragment but not all rows. Sometimes the app may be crashed because out of memory.
Can someone give me some advices? Thanks.
MainActivity.java
package com.me.test05;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(new MyArrayAdaptor(this, R.layout.row));
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
private static final String[] allnames = { "John", "Marry", "Smith", "Felicity", "Lion", "Math" };
public static class MyArrayAdaptor extends ArrayAdapter<String> {
private final Context context;
public MyArrayAdaptor(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public int getCount() {
return allnames.length * 100;
}
#Override
public String getItem(int position) {
return allnames[position % allnames.length];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
String str = getItem(position);
textView.setText(str);
FragmentTransaction ft = ((Activity) context).getFragmentManager().beginTransaction();
ft.replace(R.id.myFrameLayout, new PlaceholderFragment());
ft.commit();
return rowView;
}
}
}
File activity.xml:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:fitsSystemWindows="true">
<ListView android:id="#+id/myListView"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:dividerHeight="2px">
</ListView>
</merge>
File row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abc" />
<FrameLayout
android:id="#+id/myFrameLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</FrameLayout>
</LinearLayout>
File fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="Button" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</LinearLayout>
Screen looks like:
I have solved that problem. The problem is the fragment manager always find (to replace by a new fragment) an id in global. That is why it always found and added all new fragments into the first row since it is the first one contains that id (as well as all other rows).
To solve the problem, I create dynamic ids which are unique for each row then replace that fixed id by them before letting fragment manager to do the rest. I also store those dynamic ids into rows' tags to reuse latter.
The new code is bellow, including the code for finding and reusing added fragments:
package com.me.test05;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
ListView myListView = (ListView) findViewById(R.id.myListView);
myListView.setAdapter(new MyArrayAdaptor(this, R.layout.row));
}
}
public static class PlaceholderFragment extends Fragment {
private View rootView = null;
private String theString = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
setString(theString);
return rootView;
}
public void setString(String str) {
theString = str;
if (theString != null && rootView != null) {
TextView textView = (TextView) rootView.findViewById(R.id.textView2);
textView.setText(str);
}
}
}
private static final String[] allnames = { "John", "Marry", "Smith", "Felicity", "Lion", "Math" };
public static class MyArrayAdaptor extends ArrayAdapter<String> {
private final Context context;
public MyArrayAdaptor(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public int getCount() {
return allnames.length * 100;
}
#Override
public String getItem(int position) {
return allnames[position % allnames.length];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;
PlaceholderFragment myFragment = null;
if (rowView == null) {
rowView = inflater.inflate(R.layout.row, parent, false);
int newId = 100000 + position;
FrameLayout layout = (FrameLayout) rowView.findViewById(R.id.myFrameLayout);
layout.setId(newId);
rowView.setTag(newId);
myFragment = new PlaceholderFragment();
FragmentTransaction ft = ((Activity) context).getFragmentManager().beginTransaction();
ft.replace(newId, myFragment, "" + newId).commit();
} else {
Integer theId = (Integer) convertView.getTag();
myFragment = (PlaceholderFragment) ((Activity) context).getFragmentManager().findFragmentById(theId);
}
String str = getItem(position);
myFragment.setString(str + ", " + position);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
textView.setText(str);
return rowView;
}
}
}
Related
I am making a fitness app, where I want to have 3 nesting :
ListView with muscle group items
ListView of exercises (appears when to click on item from the muscle group ListView)
and description of exercise.
Something like this design:
But I don't know how do realize this.
Do I need create a new fragment to each item or I can use ViewPager here(if yes,how to do this)?
Give me advice,please, how to realize this design (any links of the same structure projects or any other examples)
thank you in advance
Here is the sample code
package com.sw.gitans201608042027;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
private static MainActivity mCurrent = null;
public static MainActivity getInstance() {
return mCurrent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrent = this;
setContentView(R.layout.activity_main);
switchFragment(new ListFragment());
}
public void switchFragment(Fragment f) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.container, f);
transaction.commit();
}
}
package com.sw.gitans201608042027;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ListFragment extends Fragment implements OnItemClickListener {
private String[] contents = { "a", "b" };
private String[] aArr = { "a1", "a2" }, bArr = { "b1", "b2" };
private SampleAdapter mAdapter;
public ListFragment(String[] contents) {
this.contents = contents;
}
public ListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.lv, container, false);
mAdapter = new SampleAdapter(getActivity(), contents);
((ListView) v.findViewById(R.id.lv)).setAdapter(mAdapter);
((ListView) v.findViewById(R.id.lv)).setOnItemClickListener(this);
return v;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (mAdapter.getItem(arg2) != null) {
if (((String) mAdapter.getItem(arg2)).equals("a") || ((String) mAdapter.getItem(arg2)).equals("b")) {
if (((String) mAdapter.getItem(arg2)).equals("a")) {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new ListFragment(aArr));
} else {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new ListFragment(bArr));
}
} else {
if (MainActivity.getInstance() != null)
MainActivity.getInstance().switchFragment(new TextFragment((String) mAdapter.getItem(arg2)));
}
}
}
}
package com.sw.gitans201608042027;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SampleAdapter extends BaseAdapter {
private String[] contents;
private LayoutInflater mInflater;
public SampleAdapter(Context ctxt, String[] contents) {
this.contents = contents;
mInflater = LayoutInflater.from(ctxt);
}
#Override
public int getCount() {
if (contents != null)
return contents.length;
else
return 0;
}
#Override
public Object getItem(int position) {
if (contents == null || position >= contents.length)
return null;
else
return contents[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.tv = (TextView) convertView.findViewById(R.id.list_txt);
convertView.setTag(holder);
} else
holder = (Holder) convertView.getTag();
holder.tv.setText(contents[position]);
return convertView;
}
private class Holder {
TextView tv;
}
}
package com.sw.gitans201608042027;
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.TextView;
public class TextFragment extends Fragment {
private String desc;
public TextFragment(String s){
desc = s;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.list_item, container, false);
((TextView)v.findViewById(R.id.list_txt)).setText(desc);
return v;
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.sw.gitans201608042027.MainActivity" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/list_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
lv.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I followed all the steps from various sources for getting listviews to work but my one
doesn't seem to display anything. This list view code(shown below) is activated with a tab fragment manager I won't put that here as to not bog you all down with code as there's a lot here already. It is most likely a problem with the ListFragment itself but I suppose it could be the adapter.
What happens is nothing gets displayed at all just the searchview that I have put in the main xml layout. I can switch freely between tabs with no crashes but just nothing displays in any of my listviews. I have another list which is a friends list(not included in this code snippet) and that uses a generic view holder interface and that one does not work either which suggests the problem is most likely in my ListFragment but I just can't pinpoint it. Any help is appreciated and I hope some can learn something from this, Thank you.
This is my adapter for the settings category list
package codeblox.com.listfragmentexample;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.ArrayList;
import codblox.com.listfragmentexample.R;
public class SettingsAdapter extends ArrayAdapter<Settings.SettingsCategories>
{
private final Activity context;
String[] text;
ArrayList<Settings.SettingsCategories> itemsCopy;
class ViewHolder
{
public TextView txt;
public CheckBox state;
public ImageView settingImg;
public EditText input;
public ToggleButton toggle;
public Button settingInfo; // click it to show what the setting does
}
public SettingsAdapter(Context context, ArrayList<Settings.SettingsCategories> items)
{
super(context, R.layout.settings_category_row, items);
this.context = (Activity) context;
this.itemsCopy = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = new ViewHolder();
int viewType = this.getItemViewType(position);
if(convertView == null)
{
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.settings_category_row, parent, false);
// initialize the view holder
holder = new ViewHolder();
holder.settingImg = (ImageView) convertView.findViewById(R.id.settingCategoryImg);
holder.txt = (TextView) convertView.findViewById(R.id.settingCategoryName);
convertView.setTag(holder);
} else {
// recycle the already inflated view
holder = (ViewHolder) convertView.getTag();
}
// fill data
holder = (ViewHolder) convertView.getTag();
String s = getItem(position).toString();
holder.txt.setText(itemsCopy.get(position).getSettingText());
holder.settingImg.setImageResource(itemsCopy.get(position).getImgResId());
return convertView;
}
}
This is my list fragment
package codeblox.com.listfragmentexample
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import codeblox.com.listfragmentexample.R;
public class Settings extends ListFragment implements View.OnLongClickListener
{
private ListView settingsList;
private ArrayList<SettingsCategories> mItems;
private ArrayAdapter<SettingsCategories> settingsAdapter;
private int numCategories;
String[] CategoryArray = new String[] {"Privacy and Security","Account","Networks","Camera Options","Storage","Accesibility","Features"};
int[] resIds = new int[] {R.drawable.security_settings_icon,R.drawable.account_settings_icon,
R.drawable.network_settings_icon,R.drawable.camera_settings_icon,R.drawable.storage_settings_icon,
R.drawable.accessibility_settings_icon,R.drawable.feature_settings_icon,};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View settingsView = inflater.inflate(R.layout.settings, container, false);
settingsList = (ListView)settingsView.findViewById(android.R.id.list);
// initialize the items list
return settingsView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
public Settings()
{
this.numCategories = CategoryArray.length;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public boolean onLongClick(View v)
{
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Object i = l.getItemAtPosition(position);
}
public class SettingsCategories
{
private String settingText;
private int imgResId;
SettingsCategories(String settingText,int imgResId)
{
this.settingText = settingText;
this.imgResId = imgResId;
}
public String getSettingText()
{
return this.settingText;
}
public int getImgResId()
{
return this.imgResId;
}
}
}
and finally these are my xml layouts (the first one is the main view and the second one is the view of a single item in the list
<?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:orientation="vertical"
>
<SearchView
android:id="#+id/searchFunction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</SearchView>
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
this represents an individual item in the list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="52dp"
android:layout_height="52dp"
android:id="#+id/settingCategoryImg"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="52dp"
android:text=""
android:id="#+id/settingCategoryName"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/settingCategoryImg"
/>
</RelativeLayout>
You are setting null adapter so it is not refreshing.
you are commented initialization part
check in the following method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
// settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
Your are using ListFragement and again inflating layout. that is not a good idea. when you are extending listfragment then inflating the layout is not required and and modify above method like:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
settingsList = getListView();
settingsList.setDivider(null);
mItems = new ArrayList<SettingsCategories>();
Resources resources = getResources();
for(int c = 0; c < numCategories; c++)
{
mItems.add(new SettingsCategories(CategoryArray[c],resIds[c]));
}
// initialize and set the list adapter
settingsAdapter = new SettingsAdapter(this.getActivity(), mItems);
//setListAdapter(new SettingsAdapter(getActivity(), mItems));
settingsList.setAdapter(settingsAdapter);
}
I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
I'm trying to create a ListView that each cell can be shifted as ViewPager.
Similar to Google Gmail app, that can shift emails in order to delete the emails.
It is working BUT showing nothing.
I created a ListView with BaseAdapter.
The Adapter create ViewPager with PagerAdapter that implements FragmentStatePagerAdapter.
The PagerAdapter activate the Fragment that supposed to show the data at the cells in the pagers.
Can you please help?
package com.tegrity.gui;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MyFregment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* simple ListView
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_view1, container, false);
ListView mMyListView = (ListView) view.findViewById(R.id.myList1);
// create the my adapter
MyAdapter mMyAdapter = new MyAdapter(getActivity());
mMyListView.setAdapter(mMyAdapter);
// This is working but without the ListView
// view = inflater.inflate(R.layout.connect_pager_view, null);
// android.support.v4.view.ViewPager myPagerUnit =
// (android.support.v4.view.ViewPager)
// view.findViewById(R.id.connect_pager);
// PagerAdapter pagerAdapter = new MyPagerAdapter(getFragmentManager(),
// 0);
// myPagerUnit.setAdapter(pagerAdapter);
return view;
}
// the data
private static ArrayList<String> mMyList0 = new ArrayList<String>();
/**
* my adapter
*/
public class MyAdapter extends BaseAdapter {
// the data
private ArrayList<String> mMyList = new ArrayList<String>();
private Context mContext;
private LayoutInflater mInflater;
public MyAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMyList.add("First line");
mMyList.add("Second line");
mMyList.add("Third line");
mMyList0 = mMyList;
}
#Override
public int getCount() {
return mMyList.size();
}
#Override
public Object getItem(int position) {
return mMyList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// optimization
if (convertView == null) {
convertView = mInflater.inflate(R.layout.connect_pager_view,
null);
}
android.support.v4.view.ViewPager myPagerUnit = (android.support.v4.view.ViewPager) convertView
.findViewById(R.id.connect_pager);
PagerAdapter pagerAdapter = new MyPagerAdapter(
getFragmentManager(), position);
myPagerUnit.setAdapter(pagerAdapter);
myPagerUnit
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
((Activity) mContext).invalidateOptionsMenu();
}
});
return convertView;
}
}
/**
* A simple pager adapter
*/
class MyPagerAdapter extends FragmentStatePagerAdapter {
// parameters from the my adapter
private int mPosition;
public MyPagerAdapter(FragmentManager fm, int position) {
super(fm);
mPosition = position;
}
#Override
public Fragment getItem(int pagePosition) {
return MyUnitFragment.create(pagePosition, mPosition);
}
#Override
public int getCount() {
return 2; // pager of 2 cells
}
}
/**
* my basic unit
*/
public static class MyUnitFragment extends Fragment {
public static final String PAGE = "page";
public static final String POSITION = "position";
private int mPageNumber;
// parameter from the my adapter
private int mPosition;
/**
* Factory method for this fragment class. Constructs a new fragment for
* the given page number.
*/
public static MyUnitFragment create(int pageNumber, int position) {
MyUnitFragment fragment = new MyUnitFragment();
Bundle args = new Bundle();
args.putInt(PAGE, pageNumber);
args.putInt(POSITION, position);
fragment.setArguments(args);
return fragment;
}
public MyUnitFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(PAGE);
mPosition = getArguments().getInt(POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
View convertView = (View) inflater.inflate(R.layout.bookmark_unit,
container, false);
// page parts
String data = mMyList0.get(mPosition);
TextView textView = (TextView) convertView
.findViewById(R.id.bookmarkText1);
switch (mPageNumber) {
case 0: {
textView.setText(data + " at the first page");
break;
}
case 1: {
textView.setText(data + " at the second page");
break;
}
}
return convertView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
}
XML for the ListView myList1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/white" >
<ListView android:id="#+id/myList1"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:divider="#drawable/course_divider"
android:dividerHeight="2dp"
android:cacheColorHint="#00000000" >
</ListView>
</LinearLayout>
XML for the Pager connect_pager_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/connect_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</android.support.v4.view.ViewPager>
The list unit my_unit.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/myText1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#color/black"
android:layout_marginLeft="6dp">
</TextView>
</LinearLayout>
ViewPager in ListView is a bad idea.
You can use this Swipe-to-Dismiss library for deleting https://github.com/romannurik/android-swipetodismiss
You go through following link to implement gmail like delete from list function:
https://github.com/47deg/android-swipelistview
What I need is a Horizontal scrollable ListView that serves as a horizontally scrollable menu.
I searched for a solution and came up with the this library.
I am trying to implement it.sephiroth.android.library.widget.AdapterView.OnItemClickListener on it.sephiroth.android.library.widget.HListView object in a DialogFragment.
I can get the list to populate but I can't seem to be able to attach listeners to the item.
I have been trying for 2 days to figure this out, but no game. This feature is still not working. So I turn to the old WWW for salvation..
This is my DialogFragment XML fragment_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="#800000"
android:descendantFocusability="blocksDescendants" >
<it.sephiroth.android.library.widget.HListView
android:id="#+id/hlvPlacesListScrollMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:scrollbars="none"
android:divider="#android:color/transparent"
/>
this is my viewitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#800000"
android:clickable="false"
android:focusable="false"
android:orientation="vertical" >
<ImageButton
android:id="#+id/ibScrollMenuImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#800000"
android:clickable="false"
android:focusable="false"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/tvScrollMenuTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:gravity="center_horizontal"
android:textColor="#f4f4f4" />
</LinearLayout>
This is my main_activity_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/llDialogFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#34f34f"
android:orientation="vertical"
tools:context=".MainActivity" >
</LinearLayout>
Pretty basic.
My MainActicity is :
package com.example.hscrollviewtest;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
LifeStatsDialogFragment menuFragment = new LifeStatsDialogFragment();
ft.add(R.id.llDialogFragment, menuFragment).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
the Dialogfrgment .java :
package com.example.hscrollviewtest;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
import it.sephiroth.android.library.widget.HListView;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LifeStatsDialogFragment extends DialogFragment implements
OnItemClickListener {
private HListView scroll;
private View rootView;
private HorizontalScrollMenuAdapter mAdapter;
final String[] IMAGE_TITLE = new String[] { "Home", "Work", "School",
"Sport" };
final int[] MENU_IMAGES = new int[] { R.drawable.ic_circle_home,
R.drawable.ic_circle_work, R.drawable.ic_circle_school,
R.drawable.ic_circle_gym };
public LifeStatsDialogFragment newInstance() {
return new LifeStatsDialogFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
mAdapter = new HorizontalScrollMenuAdapter(getActivity(),
R.layout.fragment_layout, R.id.tvScrollMenuTitle, IMAGE_TITLE,
MENU_IMAGES);
scroll = (HListView) rootView
.findViewById(R.id.hlvPlacesListScrollMenu);
scroll.setAdapter(mAdapter);
scroll.invalidate();
scroll.setOnItemClickListener(this);
for (int i = 0; i < scroll.getAdapter().getCount(); i++) {
Log.i(this.getClass().getSimpleName(), "first item in scroll : "
+ scroll.getChildAt(i) + "and its clickable?? "
+ scroll.getAdapter().getItemViewType(i) + "\n");
}
Log.i(this.getClass().getSimpleName(),
"The number of children for HlistView is: "
+ scroll.getParent().toString());
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
and this is the adapter(which works when I use it in the HorizontalVariableListViewDemo):
package com.example.hscrollviewtest;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
public class HorizontalScrollMenuAdapter extends ArrayAdapter<String>{
private String[] mButtonText;
private int[] mIconId;
private final String TAG = this.getClass().getSimpleName();
//Constructor
public HorizontalScrollMenuAdapter(Context context, int resource,
int textViewResourceId, String[] menuItemName, int[] menuItemImage) {
super(context, resource, textViewResourceId, menuItemName);
// TODO Auto-generated constructor stub
mButtonText = menuItemName;
mIconId = menuItemImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mIconId.length;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater mInflater = (LayoutInflater) parent.getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.viewitem, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.tvScrollMenuTitle);
holder.icon=(ImageButton) convertView.findViewById(R.id.ibScrollMenuImage);
//holder.icon.setBackgroundResource(android.R.color.transparent);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(mButtonText[position]);
holder.icon.setImageResource(mIconId[position]);
holder.icon.setTag(mIconId[position]);
Log.d(TAG,"returned view to fragment");
return convertView;
}
static class ViewHolder{
TextView name;
ImageButton icon;
}
}
I hope one of you can see my blindspot.
Thaks
Probably you are implementing the wrong OnItemClickListener.
Try to use
public class LifeStatsDialogFragment extends DialogFragment implements
it.sephiroth.android.library.widget.AdapterView.OnItemClickListener {
//...
}
I would try 2 things:
Put the fragment in the xml layout in the first place, and avoid add in the onCreate.
What happens in the onItemClick? - its currently empty. Try using an independent onItemClickListener:
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT);
}
});