I want to use the SearchView widget to filter Data.
The filtering doesnt work since i switched to a custom layout for the Listview. The ListView gets filled with all Songs i have but then doesnt update when something gets typed into the SearchView. I just want to get SearchView working for Custom ListView. If u have any Helpful Links pls share them with me.
Search Class:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SearchView;
import java.util.ArrayList;
import univie.g02.t06.tmsd.dummydata.DummyAPIData;
import univie.g02.t06.tmsd.dummydata.DummySong;
import univie.g02.t06.tmsd.MyAdapter;
public class Search extends AppCompatActivity {
ListView listV;
ArrayList<String> listItems = new ArrayList<String>();
ArrayList<String> titles = new ArrayList<String>();
ArrayList<DummySong> listSongs = new ArrayList<DummySong>();
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listV = (ListView) findViewById(R.id.list_view);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
listSongs = DummyAPIData.getAllDummySongs();
for (int i = 0; i < listSongs.size(); i++) {
listItems.add(listSongs.get(i).getDummyArtistTitle());
titles.add(listSongs.get(i).getDummyTitle());
}
adapter = new MyAdapter(this,
android.R.layout.simple_list_item_1,
listItems);
listV.setAdapter(adapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
listV.setAdapter(adapter);
return true;
}
#Override
public boolean onQueryTextSubmit(String query){
return true;
}
});
}
}
MyAdapter Class:
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.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends ArrayAdapter implements Filterable {
private List<String> list;
ArrayList<String> origData = new ArrayList<String>();
private Context context;
public MyAdapter(Context context, int resources, ArrayList<String> list) {
super(context, resources, list);
this.list = list;
this.context = context;
this.origData = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.customlayout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
customlayout.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_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="add" />
</RelativeLayout>
activitysearch.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="univie.g02.t06.tmsd.Search">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true" />
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/search_view" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
SearchView searchView =(SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
adapterQuote.getFilter().filter(s);
listView.setAdapter(adapterQuote);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
adapterQuote.getFilter().filter(s);
return false;
}
});
Related
My problem is that my listView doesn't show any items. I entered multi columns data to my SQLite database and I want to show it in a custom listview, but my listView doesn't show anything. I think the the problem is in my custom adapter and specifically in the getView() method. I track the data flow with Log messages and and the data stored in the database into an ArrayList but seems that getView() don't put values into TextView. I tried many tutorials but it keeps make me made Custom Data Class and change my hole code. PLEASE help me. I have been in this problem for weeks.
My custom adapter
ListAdapter
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> items;
public ListAdapter(Activity context, ArrayList<String> items) {
super(context, R.layout.custom_list, items);
// TODO Auto-generated constructor stub
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.custom_list, null,true);
TextView nameTV = rowView.findViewById(R.id.nameTV);
TextView priceTV = rowView.findViewById(R.id.priceTV);
//nameTV.setText(names[position]);
//priceTV.setText(prices[position].toString());
nameTV.setText(items.get(2*position));
priceTV.setText(items.get(2*position+1));
Log.d("ListAdapter", "nameTV.setText: items.get(2*position) "+nameTV+"/////////////////////////////");
Log.d("ListAdapter", "priceTV.setText: items.get(2*position) "+priceTV+"/////////////////////////////");
Log.d("ListAdapter", "getView : -----------------------------");
return rowView;
}
}
my main activity
ListDataActivity
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.support.v7.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListDataActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
ListView listView;
ArrayList<String> listData;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
databaseHelper = new DatabaseHelper(this);
listView = findViewById(R.id.listView);
listData = new ArrayList<String>();
listAdapter = new com.example.barcodescanner.ListAdapter(this,listData);
listView.setAdapter(listAdapter);
popListView();
}
private void popListView() {
Log.d("ListDataActivity","Displaying data in the ListView");
//get data and append to a list
Cursor data = databaseHelper.getData();
listData = new ArrayList<>();
while (data.moveToNext()) {
//get the data from the columns
//then add it to the ArrayList
listData.add(data.getString(1));
listData.add(data.getString(2));
Log.d("DatabaseHelper", "addData: Adding "+data.getString(1)+"+++++++++++++++++++++++++++++");
Log.d("DatabaseHelper", "addData: Adding "+data.getString(2)+"+++++++++++++++++++++++++++++");
//create the list adapter and set the adapter
//final ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(listAdapter);
//set an OnClickListener to the listView
//we can use Object for data type here
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
String price = adapterView.getItemAtPosition(i).toString(); // we can use Object for data type here
Log.d("ListDataActivity", "onItemClick: You Clicked on " + name);
Cursor data = databaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()){
itemID = data.getInt(0);
}
if (itemID > -1){
Log.d("ListDataActivity","onItemClick: the ID is : "+itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this,EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
editScreenIntent.putExtra("price",price);
startActivity(editScreenIntent);
//finish();
}else {
toastMessage("No ID associate with this name");
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.search_menu,menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<String> userslist = new ArrayList<>();
for(String user : listData){
if(user.toLowerCase().contains(newText.toLowerCase())){
userslist.add(user);
}
}
//ArrayAdapter<String> adapter = new ArrayAdapter<>(ListDataActivity.this,
// android.R.layout.simple_list_item_1,userslist);
listView.setAdapter(listAdapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
//customized toast message
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
}
my custom list layout
custom_list
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="100dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
<TextView
android:id="#+id/priceTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:textColor="#4d4d4d"
/>
</LinearLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_list_data
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListDataActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</ListView>
</android.support.constraint.ConstraintLayout>
In your onCreate method you are passing an empty ArrayList into your adapter. You then call popListView and then re-initialize your listData variable to a new object (new ArrayList()). So your adapter never receives any data.
Move the call to popListView up 2 lines to before you create your adapter.
UPDATE
Create a new class as follows:
class DataStructure {
private String name;
private String price;
DataStructure(String name, String price) {
this.name = name;
this.price = price;
}
String getName() {
return name;
}
String getPrice() {
return price;
}
}
Then change your adapter type with class ListAdapter extends ArrayAdapter<DataStructure>
Change listData to type ArrayList<DataStructure>.
When you read from the database create a new instance of DataStructure and add each instance to your list.
I have dynamic CheckBoxes and now I want to check which CheckBox clicked or not
AdditionalInformation.Java File Here Simple Adapter is defined :
package com.example.ahmad.cvbuilder21;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AdditionalInformation extends ActionBarActivity {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_infromation);
cb=(CheckBox)findViewById(R.id.additionalchk);
ABC s = ABC.getSingletonObject();
String[][] str = s.getString();
ListView lv=((ListView)findViewById(R.id.additionallist));
String[] additionalOptions={"Add your Picture","Add Experince / Project","Add Reference","Add Skills / Languages"};
String[] txtViewNames={"options"};
List<HashMap<String,String>>list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < additionalOptions.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("options", additionalOptions[i]);
list.add(map);
}
SimpleAdapter simpleAdpt = new SimpleAdapter(this, list, R.layout.mylayout2,txtViewNames , new int[] {R.id.additionaltxt1});
lv.setAdapter(simpleAdpt);
}
public void additionalData(View view1)
{
if(cb.isChecked())
{
cb.findViewById(R.id.additionalchk).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast toast = Toast.makeText(getApplicationContext(), "Checked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();
}
}
);
}
else{}
}
}
AdditionalInformation.xml file: where additionalData function is called to
check which CheckBox clicked.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Additional Options:"
android:id="#+id/additionalBtn"
/>
<ListView
android:layout_below="#id/additionalBtn"
android:layout_centerHorizontal="true"
android:id="#+id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
<Button
android:layout_below="#id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to CV"
android:onClick="additionalData"
/>
</RelativeLayout>
mylayout2.xml file where I define the controls for simple adapter:
<?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:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/additionaltxt1"
/>
<CheckBox
android:layout_alignParentRight="true"
android:layout_alignRight="#id/additionaltxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/additionalchk"
/>
</RelativeLayout>
What you actually need to do is create a custom adapter. In that custom you could listen for checkbox event at the right position.
Here is an example:
public class ListEmployeesAdapter extends BaseAdapter {
public List<Employees> items;
Context c;
public ListEmployeesAdapter(Context c, List<Employees> items) {
this.c = c;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
c.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.employee_item, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(items.get(position).name);
name.setOnCLickListener(new OnClickListener(){
#Override
public void onClick(){
//listen to the click
}
});
return convertView;
}
}
Just replace the the layout with you layout and call checkbox instead of TextView and you are good to go.
I am learning to make a simple time table managing application.
I have a list of courses displayed. Each item in a list is a textview + a delete button. The onClick Listener in my list item isn't working as expected. When I click on the delete button, it is working fine. However, I want to open up some other activity when user clicks on the textview of the list item.
Code:
ShowAll.java (the main activity in which I am displaying a list of classes)
package com.example.android.mytimetable;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ShowAll extends ActionBarActivity {
private ArrayAdapter<String> adapter ;
ArrayList <ClassDetail> classesDetail ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all);
this.bindAdapter();
ListView listView = (ListView) this.findViewById(R.id.class_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.v("Item", "clicked");
Intent intent = new Intent(view.getContext(), ShowAllClicked.class);
ClassDetail classDetail = classesDetail.get(i);
Bundle bundle = new Bundle();
bundle.putString("CLASS_NAME", classDetail.class_name);
bundle.putString("BUILDING", classDetail.building);
bundle.putString("MONDAY_START", classDetail.monday_start);
bundle.putString("MONDAY_END", classDetail.monday_end);
bundle.putString("TUESDAY_START", classDetail.tuesday_start);
bundle.putString("TUESDAY_END", classDetail.tuesday_end);
bundle.putString("WEDNESDAY_START", classDetail.wednesday_start);
bundle.putString("WEDNESDAY_END", classDetail.wednesday_end);
bundle.putString("THURSDAY_START", classDetail.thursday_start);
bundle.putString("THURSDAY_END", classDetail.thursday_end);
bundle.putString("FRIDAY_START", classDetail.friday_start);
bundle.putString("FRIDAY_END", classDetail.friday_end);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
void bindAdapter() {
DBHelper db = new DBHelper(this);
classesDetail = db.getClassesDetail();
ArrayList <String> classes = new ArrayList<>();
for(int i = 0 ; i < classesDetail.size() ; i++) {
Log.v("Adding ", classesDetail.get(i).class_name);
classes.add(classesDetail.get(i).class_name);
}
if(classes.size() == 0)
((TextView) this.findViewById(R.id.holiday)).setText(getString(R.string.noClass));
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(classes, this);
((ListView) this.findViewById(R.id.class_list)).setAdapter(customArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_show_all, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
activity_show_all.xml (the xml layout of ShowAll.java)
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.mytimetable.ShowAll"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/class_list"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/holiday"/>
</LinearLayout>
CustomArrayAdapter.java (The custom array adapter file)
package com.example.android.mytimetable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Aman Goel on 02-08-2015.
*/
public class CustomArrayAdapter extends BaseAdapter implements ListAdapter {
private ArrayList <String> list = new ArrayList<String>();
private Context context;
public CustomArrayAdapter(ArrayList <String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
((TextView) view.findViewById(R.id.list_item)).setText(list.get(position));
Button deleteBtn = (Button) view.findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper db = new DBHelper(context);
db.deleteClass(list.get(position));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
list_item.xml (The layout of each list view)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/delete"
android:id="#+id/delete"/>
</LinearLayout>
I tried to take help from here: Set onClickListener into custom adapter and here: Where should I place the onClickListener on a Custom ListView?
However, I am still not able to make the adapter work. Any help would be appreciated
set on custom adapter getview function
TextView lst_tv=(TextView)view.findViewById(R.id.list_item);
lst_tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
customArrayAdapter.setOnItemClickListener(...)
I have followed this link to learn about implementing custom spinner. My requirement is just to get drop down menu on clicking a image, it should be like a drop down menu where in i load contents to the list from backend.
But i thought that sample example posted in the above link would work. but its not giving any list on clicking a image icon.
Here is the full source code.
package com.example.testdroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.internal.widget.IcsSpinner;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.ActionMode.Callback;
public class MainActivity extends SherlockActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createCustomActionBar();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
private void createCustomActionBar()
{
List<String> links = new ArrayList<String>();
links.add("Abc");
links.add("Def");
links.add("Ghi");
LinksAdapter linkAdapter = new LinksAdapter(this, R.layout.externallink, links);
View customNav = LayoutInflater.from(this).inflate(R.layout.custom_show_action_bar, null);
IcsSpinner spinner = (IcsSpinner)customNav.findViewById(R.id.spinner);
spinner.setAdapter(linkAdapter);
ImageView refresh = (ImageView) customNav.findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
ImageView settings = (ImageView) customNav.findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
getSupportActionBar().setCustomView(customNav, new ActionBar.LayoutParams(Gravity.RIGHT));
getSupportActionBar().setDisplayShowCustomEnabled(true);
}
private static class LinksAdapter extends ArrayAdapter<String> {
private List<String> strings;
private Context context;
private LinksAdapter(Context mainActivity, int textViewResourceId, List<String> objects) {
super(mainActivity, textViewResourceId, objects);
this.strings = objects;
this.context = mainActivity;
}
#Override
public int getCount() {
if (strings == null) return 0;
return strings.size();
}
#Override
public String getItem(int position) {
return super.getItem(position);
}
// return views of drop down items
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
final String siteLink = strings.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// at 0 position show only icon
TextView site = (TextView) inflater.inflate(R.layout.externallink, null);
site.setText(siteLink);
site.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(siteLink.getUrl()));
//context.startActivity(i);
}
});
return site;
}
// return header view of drop down
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.custom_show_action_bar, null);
}
}
}
Here is my XML file, i.e layout xml file.
custom_show_action_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="right"
>
<com.actionbarsherlock.internal.widget.IcsSpinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingRight="20dp"
android:layout_gravity="center"
/>
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher"
android:paddingRight="20dp"
android:paddingLeft="10dp"
android:layout_gravity="center"
android:background="#ffffff"
android:id="#+id/refresh"/>
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher"
android:paddingRight="20dp"
android:background="#ffffff"
android:layout_gravity="center"
android:id="#+id/settings"/>
</LinearLayout>
External_links.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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Guide me where i'm wrong.
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;
}