Im having hard time integrating search in a custom listview. I have a listview using layout.xml and adapter then when I added search in my existing listview the search is working but the layout in not show in the list.Kindly click here for the file
Android Zip Click here.
Main Activity
public class MainActivity extends Activity{
EditText search;
ListView listview;
ArrayList<Person> list=new ArrayList<Person>();
ArrayList<Person> source=new ArrayList<Person>();
ArrayAdapter<Person> adapter;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
this.search=(EditText) this.findViewById(R.id.editText1);
this.listview=(ListView) this.findViewById(R.id.listView1);
//populate source
//list.add(new Person(R.drawable.melvin,"Melvin ","PhD Educational Management"));
source.add(new Person(R.drawable.dennis,"Dennis ","Master in Information Technology"));
source.add(new Person(R.drawable.jonathan,"Jonathan ","PhD in Technological Management"));
source.add(new Person(R.drawable.bell,"Bell ","MS Information Technology"));
source.add(new Person(R.drawable.jennifer,"Jennifer ","PhD Technological Management"));
source.add(new Person(R.drawable.gian,"Gian","MS Information Technology"));
//delegatethe list to the adapter
adapter=new ArrayAdapter<Person>(this,android.R.layout.simple_list_item_1,list);
//delegate the adapter to the listview
this.listview.setAdapter(adapter);
//delegate a key watcher
this.search.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
//clear the listview
list.clear();
//get match
String regex=arg0.toString();
Pattern p=Pattern.compile(regex);
for(int i=0;i<source.size();i++){
Matcher m=p.matcher((CharSequence) list.get(i));
while(m.find()){
list.add(source.get(i));
adapter.notifyDataSetChanged();
}
}
}
});
}
Adapter
package com.example.searchlist;
public class ItemAdapter extends BaseAdapter {
Context context;
ArrayList<Person> list;
LayoutInflater inflater;
public ItemAdapter(Context context, ArrayList<Person> list) {
super();
this.context = context;
this.list = list;
this.inflater=LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
PersonHandler handler =null;
if(arg1==null){
arg1=inflater.inflate(R.layout.item_layout, null);
handler=new PersonHandler();
handler.iv=(ImageView) arg1.findViewById(R.id.imageView1);
handler.name=(TextView) arg1.findViewById(R.id.textView1);
handler.course=(TextView) arg1.findViewById(R.id.textView2);
arg1.setTag(handler);
}
else handler=(PersonHandler) arg1.getTag();
handler.iv.setImageResource(list.get(arg0).getImg());
handler.name.setText(list.get(arg0).getName());
handler.course.setText(list.get(arg0).getCourse());
return arg1;
}
static class PersonHandler{
ImageView iv;
TextView name, course;
}
}
layout
<?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="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0000ff" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#ff0000" />
</LinearLayout>
Activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4682b4"
android:orientation="vertical"
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=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:ems="10"
android:hint="SEARCH"
android:padding="10dp" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#fafad2" >
</ListView>
</LinearLayout>
Related
I am a beginner in android.I have a ListView containing a spinner,edittext and an imagebutton which is for deleting that row.The spinner is populated from a list.There is a add button which add these item to the listview when each time it clicks.If i select an item in a spinner then i need to remove that item from all the other spinner in that listview and also the items become visible when i deleted the selected spinner row or change the selected item in the spinner.Say for simplicity that my Spinners are populated with the following data:
{"data1", "data2", "data3", "data4", "data5"};
For example, if I select my first ListView's Spinner value to be "data3" and then the "data3" entry disappears from all the other ListView Spinner and this will appears back only when i change the selected value in the first listview spinner or deleting that row, similarly for each ListView spinner.How to do this? Somebody please help me.Below is my code.
receipt_trans.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" >
<LinearLayout
android:id="#+id/LinLay3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtGrossAmt"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:text="Gross amount :"
android:textColor="#000" />
<EditText
android:id="#+id/edtGrossAmt"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:background="#drawable/border"
android:focusableInTouchMode="false"
android:layout_toRightOf="#+id/txtAccount" />
<Button
android:id="#+id/btnAddRow"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_marginLeft="10dp"
android:text="Add Row"
android:layout_toRightOf="#+id/edtGrossAmt" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinLay4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/txtFundStores"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="Fund Stores"
android:textColor="#000" />
</LinearLayout>
<ListView
android:id="#+id/lstFundStore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
</ListView>
</LinearLayout>
fundstore_row.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="horizontal" >
<Spinner
android:id="#+id/spnAccount"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/textView1" />
<EditText
android:id="#+id/edtAccAmount"
android:layout_width="0sp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:inputType="numberDecimal"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<ImageButton
android:id="#+id/imgDel"
android:layout_width="20sp"
android:layout_height="fill_parent"
android:contentDescription="delete"
android:src="#drawable/delete2" />
</LinearLayout>
ReceiptTransaction.java:
public class ReceiptTransaction extends Activity{
RestTemplate restTemplate=new RestTemplate();
String constr="http://192.168.1.14:8080/ServPro/stock/";
ListView lstFund;
Button btnAddRw;
private FundStoreAdapter adapter;
ArrayList<COAAccount> subList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.receipt_trans);
lstFund=(ListView) findViewById(R.id.lstFundStore);
btnAddRw=(Button) findViewById(R.id.btnAddRow);
setFundStore();
setDeduction();
btnAddRw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
});
}
public void setFundStore(){
String accList=restTemplate.getForObject(constr+"getAllCBOnly", String.class);
Gson gson = new Gson(); // Or use new GsonBuilder().create();
CoaAccountList dropCoaList = gson.fromJson(accList, CoaAccountList.class);
subList=new ArrayList<COAAccount>();
COAAccount newAccount = new COAAccount();
newAccount.setFunds(-1, -2, "Select...", "select", "SE",0.0f);
subList.add(newAccount);
ArrayList<COAAccount> listItem=(ArrayList<COAAccount>) dropCoaList.getCoaList();
for(COAAccount addCoa:listItem){
subList.add(addCoa);
}
adapter=new FundStoreAdapter(ReceiptTransaction.this, R.layout.fundstore_row, new ArrayList<FundReceipt>(),subList);
lstFund.setAdapter(adapter);
adapter.add(new FundReceipt(subList.get(0), 0.0f));
}
public void setDeduction(){
}
}
FundStoreAdapter.java:
public class FundStoreAdapter extends ArrayAdapter<FundReceipt> {
protected static final String LOG_TAG = FundStoreAdapter.class.getSimpleName();
private final Context context;
private final int resourceID;
private List<FundReceipt> items;
private ArrayList<COAAccount> list;
public FundStoreAdapter(Context context, int resource, List<FundReceipt> items, ArrayList<COAAccount> subList) {
super(context, resource,items);
this.context = context;
this.resourceID = resource;
this.items=items;
this.list=subList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FundStoreHolder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View rowView = inflater.inflate(resourceID, parent, false);
holder=new FundStoreHolder();
holder.fundRecpt=items.get(position);
holder.imgDeleteFund=(ImageButton) rowView.findViewById(R.id.imgDel);
holder.imgDeleteFund.setTag(holder.fundRecpt);
removeRow(holder);
holder.edtAmount=(EditText) rowView.findViewById(R.id.edtAccAmount);
setValueTextListeners(holder);
holder.spnAcct=(Spinner) rowView.findViewById(R.id.spnAccount);
setNameTextChangeListener(holder);
rowView.setTag(holder);
setupItem(holder);
return rowView;
}
private void removeRow(FundStoreHolder holder) {
holder.imgDeleteFund.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FundReceipt itemToRemove = (FundReceipt)v.getTag();
remove(itemToRemove);
}
});
}
private void setupItem(FundStoreHolder holder) {
holder.edtAmount.setText(String.valueOf(holder.fundRecpt.getAmount()));
//ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
ArrayAdapter<COAAccount> dataAdapter =new ArrayAdapter<COAAccount>(context, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spnAcct.setAdapter(dataAdapter);
holder.spnAcct.setSelection(dataAdapter.getPosition(holder.fundRecpt.getSelAcct()));
}
public static class FundStoreHolder{
FundReceipt fundRecpt;
Spinner spnAcct;
EditText edtAmount;
ImageButton imgDeleteFund;
}
private void setNameTextChangeListener(final FundStoreHolder holder) {
holder.spnAcct.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
holder.fundRecpt.setSelAcct((COAAccount) parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
private void setValueTextListeners(final FundStoreHolder holder) {
holder.edtAmount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
holder.fundRecpt.setAmount(Float.parseFloat(s.toString()));
}catch (NumberFormatException e) {
Log.e(LOG_TAG, "error reading float value: " + s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
}
FundReceipt.java:
public class FundReceipt implements Serializable {
private static final long serialVersionUID = -5435670920302756945L;
private Float amount = 0.0f;
private COAAccount selAcct;
public FundReceipt(COAAccount selAcct, Float amount) {
this.setAmount(amount);
this.setSelAcct(selAcct);
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public COAAccount getSelAcct() {
return selAcct;
}
public void setSelAcct(COAAccount selAcct) {
this.selAcct = selAcct;
}
}
I faced same problem but i could succeed to remove selected item from list After that i did an alter net. Selected item shown highlighted state in drop down list. I know my answer was not fulfill your question but want to share with you.
Your spinner:
<Spinner
android:id="#+id/sp_handi_cap"
style="#style/SpinnerAppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="#drawable/selector_rectangular_gray_trans_bg"
android:descendantFocusability="afterDescendants"
android:gravity="start"
android:minWidth="250dp"
android:padding="5dp"
android:singleLine="true" />
selector_rectangular_gray_trans_bg.xml
<solid android:color="#android:color/transparent" />
<stroke
android:width="1dp"
android:color="#color/gray6" />
<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" /></shape>
Create layout :
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/selector_spinner_item_activited"
android:gravity="center"
android:padding="3dp"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textSize="12sp" />
selector selector_spinner_item_activited.xml :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/selector_rectangular_black_trans_bg" android:state_activated="true"/>
<item android:drawable="#android:color/transparent"/>
</selector>
Create adapter :
ArrayAdapter objAdapter = new ArrayAdapter<String>(AddStudentActivity.this,
R.layout.layout_text_single_line_activated, getResources()
.getStringArray(R.array.arr_handicap_option));
set adapter in spinner object.
spinner.setAdapter(objAdapter);
I'm trying to implement Custom ListView (i.e. ListView with custom Adapter) with Search Box, for that I have written the following XML code--
<LinearLayout 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:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
My MenuListActivity code is---
public class MenuListActivity extends Activity
{
ListView list;
TextView txtInputSearch;
MenuListAdapter adapter;
public MenuListActivity CustomListView = null;
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_list);
CustomListView = this;
setListData();
Resources res =getResources();
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
list= ( ListView )findViewById( R.id.list ); // List defined in XML ( See Below )
adapter=new MenuListAdapter( CustomListView, CustomListViewValuesArr,res );
list.setAdapter( adapter );
txtInputSearch.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
String text = txtInputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
});
}
public void setListData()
{
for (int i = 0; i < 11; i++)
{
final ListModel objListModel = new ListModel();
objListModel.setMenu("Company "+i);
objListModel.setPrice("com.androidexample.customlistview:drawable/rihanna");
// sched.setUrl("http:\\www."+i+".com");
CustomListViewValuesArr.add(objListModel);
}
}
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
// SHOW ALERT
Toast.makeText(CustomListView,"Clicked",Toast.LENGTH_LONG).show();
}
}
See my Adapter class Below--
public class MenuListAdapter extends BaseAdapter implements OnClickListener
{
private Activity activity;
private ArrayList data;
private ArrayList<ListModel> arrayList;
private static LayoutInflater inflater=null;
public Resources res;
ListModel tempValues=null;
int i=0;
public MenuListAdapter(Activity paramActivity, ArrayList paramDataList, Resources paramResource)
{
activity = paramActivity;
data=paramDataList;
res = paramResource;
arrayList=new ArrayList<ListModel>();
arrayList.addAll(data);
inflater = ( LayoutInflater )activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
public TextView item_name;
public TextView item_price;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.menu_list_row, null);
holder = new ViewHolder();
holder.item_name = (TextView) vi.findViewById(R.id.item_name);
holder.item_price=(TextView)vi.findViewById(R.id.item_price);
// holder.image=(ImageView)vi.findViewById(R.id.list_image);
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
if(data.size()<=0)
{
holder.item_name.setText("No Data");
}
else
{
tempValues=null;
tempValues = ( ListModel ) data.get( position );
holder.item_name.setText( tempValues.getMenu() );
holder.item_price.setText( tempValues.getPrice());
/* holder.image.setImageResource(
res.getIdentifier(
"com.androidexample.customlistview:drawable/"+tempValues.getImage()
,null,null));*/
vi.setOnClickListener(new OnItemClickListener( position ));
}
return vi;
}
public void onClick(View v)
{
Log.v("CustomAdapter", "=====Row button clicked=====");
}
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
OnItemClickListener(int position)
{
mPosition = position;
}
public void onClick(View arg0)
{
MenuListActivity sct = (MenuListActivity)activity;
sct.onItemClick(mPosition);
}
}
// Filter Class
public void filter(String charText)
{
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0)
{
data.addAll(arrayList);
}
else
{
for (ListModel lm : arrayList)
{
if (lm.getMenu().toLowerCase(Locale.getDefault()).contains(charText))
{
data.add(lm);
}
}
}
notifyDataSetChanged();
}
}
In design mode, when I clicks on Graphical Layout It is showing me proper/expected view (i.e. Search box to the Top and ListView Below to the search Box) but when I run my application then it is showing only ListView and SearchBox (EditText) is invisible. Please Help.
Change listview layout height to android:layout_height="0dp" instead of android:layout_height="fill_parent"
<LinearLayout 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:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginTop="20dp"
android:layout_weight="1" />
</LinearLayout>
Edit Use RelativeLayout instead of LinearLayout as
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:completionThreshold="1"
android:singleLine="true"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:layout_weight="1"
android:layout_below="#+id/txtInputSearch"
android:drawSelectorOnTop="false"/>
</RelativeLayout>
Edit
Use EditText in your code instead of TextView ,So change
TextView txtInputSearch;
to
EditText txtInputSearch;
And
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
to
txtInputSearch=(EditText )findViewById(R.id.txtInputSearch);
The problem is that you are adding a weight into you ListView which would take all the space of your layout, instead dont put any weight on it just simply wrap its height and remove the android:layout_weight="1"
sample:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".CustomListViewAndroidExample" >
<EditText
android:id="#+id/txtInputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search item.."
android:inputType="textVisiblePassword" />
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
</LinearLayout>
problem:
txtInputSearch=(TextView)findViewById(R.id.txtInputSearch);
You are casting it to a TextView not an EditText.
change it to this:
EditText txtInputSearch;
txtInputSearch=(EditText)findViewById(R.id.txtInputSearch);
I have a model class. Now from my activity i want to set the values in model class & show them in gridview using my custom adapter. After that i need to store the object in a variable(class type) from gridview's onItemClick. I have done the below codes. But its not working. Where did i go wrong?
activity_country.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=".CountryActivity" >
<TextView
android:id="#+id/nTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="26dp"
android:text="Name" />
<TextView
android:id="#+id/aTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nTextView"
android:layout_below="#+id/nTextView"
android:layout_marginTop="24dp"
android:text="About" />
<EditText
android:id="#+id/CountryNameEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/nTextView"
android:layout_alignBottom="#+id/nTextView"
android:layout_marginLeft="48dp"
android:layout_toRightOf="#+id/nTextView"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/CountryAboutEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryNameEditText"
android:layout_alignTop="#+id/aTextView"
android:ems="10" />
<Button
android:id="#+id/saveCountryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/CountryAboutEditText"
android:layout_below="#+id/CountryAboutEditText"
android:layout_marginLeft="16dp"
android:layout_marginTop="22dp"
android:text="Save"
android:onClick="saveCountry"
/>
<GridView
android:id="#+id/countryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/saveCountryButton"
android:layout_centerHorizontal="true"
android:numColumns="2">
</GridView>
</RelativeLayout>
CountryActivity.java
public class CountryActivity extends Activity
{
ArrayList<Country> countries = new ArrayList<Country>();
Country aCountry;
EditText CountryNameTxtBox;
EditText CountryAboutTxtBox;
GridView countrygGridView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country);
// Show the Up button in the action bar.
setupActionBar();
CountryNameTxtBox = (EditText)findViewById(R.id.CountryNameEditText);
CountryAboutTxtBox = (EditText)findViewById(R.id.CountryAboutEditText);
countrygGridView = (GridView)findViewById(R.id.countryGridView);
}
public void saveCountry(View view)
{
String txtName = CountryNameTxtBox.getText().toString();
String txtAbout = CountryAboutTxtBox.getText().toString();
showGrid();
}
public void showGrid()
{
/*
ArrayAdapter<Country> adapter = new ArrayAdapter<Country>(this,android.R.layout.simple_list_item_1, countries);
countrygGridView.setAdapter(adapter);
*/
countrygGridView.setAdapter(new myAdapter(this,countries));
countrygGridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
for(Country mCountry: countries)
{
if(countries.contains(aCountry))
{
Toast.makeText(CountryActivity.this,countries.get(position).getName(), 2000).show();
}
}
}
});
}
countrygrid.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="horizontal" >
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:layout_marginTop="15sp"
android:textSize="15sp" >
</TextView>
</LinearLayout>
myAdapter.java
public class myAdapter extends BaseAdapter
{
Context mycontext;
ArrayList<Country> countries;
public myAdapter(Context c, ArrayList<Country> obj)
{
this.mycontext=c;
this.countries = obj;
}
public int getCount() {
// TODO Auto-generated method stub
return countries.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return countries.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertview, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if(convertview==null)
{
gridView =new View(mycontext);
gridView =inflater.inflate(R.layout.countrygrid, null);
TextView txtvw1 = (TextView) gridView.findViewById(R.id.label1);
txtvw1.setText(countries.get(position).getName());
TextView txtvw2 = (TextView) gridView.findViewById(R.id.label2);
txtvw2.setText(countries.get(position).getAbout());
}
else
{
gridView = (View) convertview;
}
return gridView;
}
}
*Its showing error in countryActivity.java- when i am trying to set the adapter inside showGrid() *
countrygGridView.setAdapter(new myAdapter(this,countries));
public class myAdapter
{
does not extend anything
It should be
public class myAdapter extends BaseAdapter //orArrayAdapter
{
If you still have a problem post the stacktrace for further help
I was trying to implement simple customlistview.What i tried to do is to inflate a text and a picture inside each list row in the listview.I got no output i.e. layout was not inflating..I got a blank screen.I used 2 Java class and 2 xml files.Below is my code..Please let me know where is my mistake and what should i correct?
CListView.java
package com.example.customlistview;
public class Clistview extends Activity {
int p1[]={R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String[] Shapes1={"circle","circle","circle","circle","circle"};
ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clistview);
lv=(ListView)findViewById(R.id.listView1);
CustomListViewAdapter clvadapter=new CustomListViewAdapter(Clistview.this,Shapes1,p1);
lv.setAdapter(clvadapter);
}
}
CustomListViewAdapter.java
package com.example.customlistview;
public class CustomListViewAdapter extends BaseAdapter {
Context context;
String shape1[];
int pic[];
public CustomListViewAdapter(Context c,String[] sh,int[] p)
{
this.context=c;
this.shape1=sh;
this.pic=p;
}
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
public String getItem(int pos) {
// TODO Auto-generated method stub
return shape1[pos];
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View v, ViewGroup vg) {
// TODO Auto-generated method stub
View itemview=v;
TextView tv1;
ImageView im1;
if(itemview==null)
{
LayoutInflater inflater=(LayoutInflater)((Activity)context).getLayoutInflater();
itemview=inflater.inflate(R.layout.clistview1,vg,false);
}
tv1=(TextView)itemview.findViewById(R.id.textView1);
im1=(ImageView)itemview.findViewById(R.id.imageView1);
tv1.setText(shape1[pos]);
im1.setImageResource(pic[pos]);
return itemview;
}
}
activity_clistview.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=".Clistview" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp" >
</ListView>
</RelativeLayout>
clistview1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
>
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="right"
/>
</LinearLayout>
Inside CustomListViewAdapter, change this
public int getCount() {
// TODO Auto-generated method stub
return shape1.length;
}
It is an important function that decides the number of items in a ListView.
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
You are returning 0 .
Return pic.length or shape1.length as per your requirement.
public int getCount() {
return pic.length;
}
Method getCount() returns the number of items in the datatset for the adapter.
getCount()
i am trying to display image using GridView. This is the first time i using GridView, so i using the example from here and implement it to mine (i have tried the example that contained there, and it's works).
But, i have checked it many time, there's no error comes from LogCat, no Force Closed, the image didn't show. i have no idea where's the wrong part.
Here's my code:
choosepic.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="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg_inner">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/book_inner"
android:layout_marginTop="50dp"
/>
<ImageButton
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/home_btn"
android:background="#null"
/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/bg_arrow_btn"
android:layout_alignParentRight="true"
/>
<ImageButton
android:id="#+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/right_arrow"
android:background="#null"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_marginRight="7dp"
android:layout_marginLeft="7dp"
/>
<ImageButton
android:id="#+id/prevBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/left_arrow"
android:background="#null"
android:layout_toLeftOf="#+id/nextBtn"
android:layout_marginTop="5dp"
/>
<GridView
android:id="#+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="30dp"
android:stretchMode="columnWidth"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="70dp"
>
</GridView>
</RelativeLayout>
animalbutton.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="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:visibility="gone">
</TextView>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
public ImageAdapter(Activity activity,ArrayList<String> listName, ArrayList<Integer> listImage) {
super();
this.listNm = listName;
this.listAnim = listImage;
this.activity = activity;
}
public static class ViewHolder
{
public ImageView imgViewAnim;
public TextView txtViewAnim;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.animalbutton, null);
view.txtViewAnim = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewAnim = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewAnim.setText(listNm.get(position));
view.imgViewAnim.setImageResource(listAnim.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listNm.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
choosepic.java
public class choosepic extends Activity {
/** Called when the activity is first created. */
ImageAdapter mAdapter;
GridView gridView;
static final String[] animal = new String[] {
"cat", "cow","croc", "duck", "elephant", "giraffe", "lion", "moose", "mouse"};
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosepic);
gridView = (GridView) findViewById(R.id.gridView1);
prepare_list1();
mAdapter = new ImageAdapter(this,listNm, listAnim);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Toast.makeText(getApplicationContext(), mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepare_list1(){
listNm = new ArrayList<String>();
listAnim = new ArrayList<Integer>();
for (int i = 0; i < animal.length; i++) {
listNm.add(animal[i]);
listAnim.add(getResources().getIdentifier("anim_"+animal[i], "drawable", getPackageName()));
}
}
}
i need some help. i appreciate any help. thank you in advance!
i think the problem is in your getCount() that returns 0 elements
instead of that make it like this
#Override
public int getCount() {
// TODO Auto-generated method stub
return listNm.size();
}