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();
}
});
}
Related
I have an ArrayList<String> List which contains some items from the listview all_list. How can I select these items in the list view all_list programmatically by checking the ArrayList<String> List contents?
for e.g., listview all_list contains [0] apple
[1] orange
[2] banana
In ArrayList<String> List, I have orange so I want item on position 1 on the listview all_list to be selected (highlighted) automatically.
I have tried using all_list.setItemChecked(), but it does nothing and shuts down the application. I am performing the operation after listing the adapter.
set an onItemClickListener to the listview such that on click, you set a boolean flag that sets the checkbox in each row to selected. then call notifyDataSetChanged()
Try this
MainActivity.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView1;
ArrayList<ModelClass> modelClass = new ArrayList<ModelClass>();
FruitSelectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelClass.add(new ModelClass("Orange", true));
modelClass.add(new ModelClass("Apple", false));
modelClass.add(new ModelClass("Banana", false));
modelClass.add(new ModelClass("Grapes", false));
listView1 = (ListView) findViewById(R.id.listView1);
adapter = new FruitSelectAdapter(MainActivity.this, modelClass);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(modelClass.get(arg2).isSelected()){
modelClass.get(arg2).setSelected(false);
}else{
modelClass.get(arg2).setSelected(true);
}
adapter.notifyDataSetChanged();
}
});
}
}
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"
tools:context="com.example.multiseekbar.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
</ListView>
</RelativeLayout>
FruitSelectAdapter.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FruitSelectAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<ModelClass> modelClass=null;
public FruitSelectAdapter(Activity activity, ArrayList<ModelClass> modelClass) {
this.activity = activity;
this.modelClass = modelClass;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return modelClass.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return modelClass.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder =new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.txtFruitName = (TextView)convertView.findViewById(R.id.txtFruitName);
holder.cbFruitSelectStatus = (CheckBox)convertView.findViewById(R.id.cbFruitSelectStatus);
holder.linLayBackground = (LinearLayout) convertView.findViewById(R.id.linLayBackground);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtFruitName.setText(modelClass.get(position).getFruitName());
holder.cbFruitSelectStatus.setChecked(modelClass.get(position).isSelected());
if(modelClass.get(position).isSelected()){
holder.linLayBackground.setBackgroundColor(Color.parseColor("#80ccff"));
}else{
holder.linLayBackground.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
class ViewHolder{
TextView txtFruitName;
CheckBox cbFruitSelectStatus;
LinearLayout linLayBackground;
}
}
row1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/linLayBackground"
android:layout_height="70dp"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtFruitName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Fruit name"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#000000" />
<CheckBox
android:id="#+id/cbFruitSelectStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
ModelClass.java
package com.example.multiseekbar;
public class ModelClass {
String fruitName;
boolean isSelected=false;
public ModelClass(String fruitName, boolean isSelected) {
this.fruitName = fruitName;
this.isSelected = isSelected;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
list.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="vertical" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab on icon to start a Campaign" />
</LinearLayout>
Activity+list_demonstration.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Active Campaign"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#4AE56B" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Closed Campaign"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="130dp" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
I m trying to make an listview that is empty in the starting of the application.in which a textview will give information to tab on icon..,and when user tab and create an app.the data shown in the listview..bt listview is giving an error ,how to solve it..
Demo.java // custom adapter
package com.example.smscampaign;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Demo extends ArrayAdapter{
private Campaign_Details list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.text1);
ImageView btn=(ImageView)v.findViewById(R.id.imageView1);
if (convertView == null) {
v = vi.inflate(R.layout.list, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.text1);
return v;
}
}
Campaign_Details.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class Campaign_Details extends Activity {
private Demo selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
DataBaseHandler info= new DataBaseHandler(this);
info.open();
String data=info.getData();
info.close();
String[] values= new String[]{ data };
//txt.setText(data);
// Button next=(Button) findViewById(R.id.next);
// Map<String, String[]> storage = new HashMap<String, String[]>();
// String[] tableItems = storage.get("ContactTable");
// next.setOnClickListener(this);
// final ListView listview = (ListView) findViewById(R.id.listview);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
listview .setEmptyView(emptyText);
// listview.setEmptyView((LinearLayout) findViewById(R.id.emptyText));
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < data.length(); ++i) {
selectedAdapter = new Demo(this,values);
selectedAdapter.setNotifyOnChange(true);
listview.setAdapter(selectedAdapter);
list.add(data);
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent n = new Intent(getApplicationContext(), SmsSend.class);
startActivity(n);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.nextPage:
Intent i = new Intent(this,SmsSend.class);
startActivity(i);
break;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE:
You have done everything wrong. you need to change as follows.
public Demo(Context context, String[] values) {
super(context, R.layout.activity_list_demostration);
this.context = context;
this.values = values;
}
to
public Demo(Context context, String[] values) {
super(context, values);
this.context = context;
this.values = values;
}
In Campaign_Details Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_demostration);
ListView listview = (ListView) findViewById(R.id.listView1);
TextView emptyText = (TextView)findViewById(android.R.id.empty);
According to your question finally you need to change here from
ListView listview = (ListView) findViewById(R.id.listView1);
to
ListView listview = (ListView) findViewById(R.id.listView);
i have android application that display a listview that extends Base Adapter to get image and text.
now i want to add a header section for this list view how to do it ? can anyone help me ???
this is how the list view is shown
what i wnat is that before the first item display a header and before the last item to display a header.
activity_group_list.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=".GroupList" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
row_list_group.xml
<?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="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/algeria_flag" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView1"
android:ems="10"
android:text="text" />
</RelativeLayout>
ItemDetails.java
package com.devleb.expandablelistdemo3;
public class ItemDetails {
String Name;
int image;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
CustomAdapter.java
package com.devleb.expandablelistdemo3;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsarrayList;
LayoutInflater layoutInflater;
String[] teamName;
int[] teamFlag;
Context context;
public CustomAdapter(ArrayList<ItemDetails> result, Context c) {
itemDetailsarrayList = result;
context = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemDetailsarrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return itemDetailsarrayList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row_list_group, parent,
false);
TextView txt = (TextView) row.findViewById(R.id.textView1);
ImageView imgv = (ImageView) row.findViewById(R.id.imageView1);
txt.setText(itemDetailsarrayList.get(position).getName());
imgv.setImageResource(itemDetailsarrayList.get(position).getImage());
return row;
}
}
GroupList.java
package com.devleb.expandablelistdemo3;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData.Item;
import android.view.Menu;
import android.widget.ListView;
public class GroupList extends Activity {
int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag,
R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain,
R.drawable.netherlands_flag, R.drawable.czech_republic_flag,
R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress,
R.drawable.cote_divoire_flag, R.drawable.japan,
R.drawable.uruguay_flag, R.drawable.costa_rica_flag,
R.drawable.england_flag, R.drawable.italy_flag,
R.drawable.switzerland, R.drawable.ecuador_flag,
R.drawable.france_flag, R.drawable.honduras_flag,
R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag,
R.drawable.nigeria_flag, R.drawable.germany_flag,
R.drawable.portugal, R.drawable.ghana_flag,
R.drawable.united_states_flag, R.drawable.belgium_flag,
R.drawable.algeria_flag, R.drawable.russia_flag,
R.drawable.korea_flag };
String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS",
"COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI",
"ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR",
"GHA", "USA", "BEL", "ALG", "RUS", "KOR" };
ItemDetails item_details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
ArrayList<ItemDetails> result = getList();
ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new CustomAdapter(result, getApplicationContext()));
}
private ArrayList<ItemDetails> getList() {
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
for (int i = 0; i <32; i++) {
item_details = new ItemDetails();
item_details.setName(name[i]);
item_details.setImage(img[i]);
results.add(item_details);
}
return results;
}
added section
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
TextView txtSection = (TextView)findViewById(R.id.textSeparator);
ArrayList<ItemDetails> result = getList();
lv = (ListView) findViewById(R.id.list);
lv.addHeaderView(txtSection);
lv.setAdapter(new CustomAdapter(result, getApplicationContext()));
}
private ArrayList<ItemDetails> getList() {
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
for (int i = 0; i <4; i++) {
item_details = new ItemDetails();
View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null);
lv.addHeaderView(layout_section );
item_details.setName(name[i]);
item_details.setImage(img[i]);
results.add(item_details);
}
return results;
}
}
log cat
03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException
03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59)
In your row_list_group.xml, create a header layout and set its visibility to gone. Then set it to visible when you need to add a header.
Or you can try what Nickolai has suggested:
This way you need to create a layout and add to the listview at the runtime in the list adapter getView method.
In GroupList in onCreate method just add the following line:
ListView lv = (ListView) findViewById(R.id.list);
lv.addHeaderView(<place your header view here>);
addHeaderView expects to get View object. So, you can place header using two ways:
//Programmatically create button (or other view, that you need) and place it:
Button b = new Button(this);
lv.addHeaderView(b);
// Create xml layout, inflate it and place into listview as header view
View yourLayout = getLayoutInflater().inflate(R.layout.your_view_layout, null);
lv.addHeaderView(yourLayout );
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);
}
});
my app has custom ListView, each row contains checkbox ,edit text and 2 buttons. In the main xml layout file i have 1 submit button and listView. i want that, when i click on submit button, i should get all checked row position.I am new to android programming ,so plz help me my code is not working here is my code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:layout_height="wrap_content"
android:text="#string/button_submit"
android:layout_width="wrap_content"
android:id="#+id/main_submit_button" android:onClick="#string/button_submit"></Button>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_weight="1"
android:id="#+id/items_name"
android:gravity="left"
android:textStyle="bold" />
<CheckBox android:id="#+id/items_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="#+id/items_add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/text_switcher_plus" />
<EditText android:digits="10"
android:textStyle="bold" android:gravity="left"
android:id="#+id/items_plates" android:layout_height="wrap_content"
android:layout_width="90dp"></EditText>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/items_minus_button"
android:text="#string/text_switcher_minus"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
VegmenuActivity
package com.sagar.resmenu;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
// reference:http://pareshnmayani.wordpress.com/tag/android-custom-listview-example
public class VegmenuActivity extends Activity implements OnItemClickListener{
//dynamic array that contains names of items
private ArrayList<String> items = new ArrayList<String>
(Arrays.asList("Veg pulav", "Pav bhaji", "Panir tikka", "veg kolhapuri",
"Coconut Rice", "Curd rice", "Mint Pulao",
"Banana Custard","Basundi", "Cheese potato Tikkis",
"Dum aloo"));
private ArrayList<Integer> counter = new ArrayList<Integer>
(Arrays.asList(0, 0,0, 0, 0,0, 0,0, 0,0,0));
private SparseBooleanArray a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView lv =(ListView)findViewById(R.id.list_view);
// lv.setOnClickListener(null);
MyAdapter adapter = new MyAdapter(getApplicationContext(),items,counter);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button submit1;
submit1 = (Button)findViewById(R.id.main_submit_button);
submit1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = lv.getCheckedItemPositions();
int len = items.size();
for (int i = 0; i < len; i++)
{
if(a.valueAt(i) == true)
Log.d("Returned ", String.valueOf(a.valueAt(i)));
}
}
});
}
//private OnItemClickListener selectCat = new OnItemClickListener();
public void onItemClick(AdapterView<?> a, View v, int positon, long id) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
package com.sagar.resmenu;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextSwitcher;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter implements OnClickListener{
private LayoutInflater inflater;
private ArrayList<String> data;
VegmenuActivity m;
private ArrayList<Integer> counter;
public MyAdapter(Context context, ArrayList<String> data,ArrayList<Integer> counter) {
// TODO Auto-generated constructor stub
super();
// Caches the LayoutInflater for quicker use
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Sets the events data
this.data= data;
this.counter=counter;
}
public int getCount() {
return this.data.size();
//return this.counter.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return null;
}
public long getItemId(int position) throws IndexOutOfBoundsException{
return 0;
}
public int getViewTypeCount(){
return 1;
}
public static class ViewHolder
{
TextView items_name;
CheckBox items_check ;
Button items_plus_button;
Button items_minus_button;
EditText plates;
}
public View getView(int position, View convertView, ViewGroup parent){
//String myText = getItem(position);
ViewHolder holder;
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.items,parent,false);
holder.items_name = (TextView) convertView.findViewById(R.id.items_name);
holder.plates = (EditText) convertView.findViewById(R.id.items_plates);
holder.items_check = (CheckBox) convertView.findViewById(R.id.items_check);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.items_name.setText(data.get(position));
holder.plates.setText(String.valueOf(counter.get(position)));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
when I need check boxes inside listview, I often code as following:
MyAdapter.java:
- Declare an boolean array to mark which item is checked/unchecked:
....
boolean[] checked;
...
inside constructor:
checked = new boolean[data.size()];
- Inside getView()
{
.....
holder.items_check.setChecked(checked[position]);
holder.items_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked[position] = isChecked;
}
});
.....
- And method to get all checked items:
boolean[] getCheckedItems() {
return checked;
}
That's !
Could it be that your getItem and getItemId only return null and 1? These methods need to return the correct data for this to work I believe. getItem would need to be:
String getItem(int position)
{
return data.get(position);
}
and getItemId would simply return position instead of 0:
String getItemId(int position)
{
return position;
}