I have spent at least a couple of hours looking at all the code online when this question is googled, yet still don't really understand how to implement this.
I have a listview populated by the database with a cursor adapter.
Every listview item has a checkbox next to it.
I want to delete all the listview items from the listview that have their checkbox selected.
What code do i need in my delete button to implement this?
Thanks and kind regards.
Before anyone mentions this has been asked before; every single question has their own implementation and code in the question, i haven't been able to find a step-by-step tutorial.
My Solution:
Here is my adapter:
public class TextCheckBoxAdapter extends ArrayAdapter {
private List<String> names;
private List<Boolean> checked;
public TextCheckBoxAdapter(Context context, List<String> names) {
super(context, R.layout.custom_row_text_checkbox, names);
this.names = names;
checked = new ArrayList<>();
for(String name : names) checked.add(false);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View customView = inflater.inflate(R.layout.custom_row_text_checkbox, parent, false);
TextView tv = (TextView) customView.findViewById(R.id.nameTv);
tv.setText(names.get(position));
final CheckBox checkBox = (CheckBox) customView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked.set(position, checkBox.isChecked());
}
});
return customView;
}
public String getName(int position){
return names.get(position);
}
public List<Boolean> getCheckList(){
return checked;
}
/**Anzahl selektierter Checkboxen*/
public int getCountSelectedCheckBoxes(){
int toReturn = 0;
for(boolean b : checked) if(b) toReturn++;
return toReturn;
}
public void delete(int i){
names.remove(i);
checked.remove(i);
notifyDataSetChanged();
}
public boolean isEmpty(){
return names.isEmpty();
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginLeft="#dimen/custom_margin_left_and_right"
android:layout_marginStart="#dimen/custom_margin_left_and_right"
android:layout_marginRight="#dimen/custom_margin_left_and_right"
android:layout_marginEnd="#dimen/custom_margin_left_and_right">
<TextView
android:id="#+id/nameTv"
android:layout_weight="0.9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/unbenannt"
android:textColor="#color/grey"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
/>
<CheckBox
android:id="#+id/checkbox"
android:layout_weight="0.1"
android:layout_gravity="center"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
//Delete via icon in toolbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
onBackPressed();
}else if(id == R.id.action_loeschen){
if(adapter.getCountSelectedCheckBoxes() > 0){
List<Boolean> checked = adapter.getCheckList();
for(int i = checked.size() - 1; i >= 0; i--){ //Rueckwaerts ausfuehren!
if(checked.get(i)){
String name = adapter.getName(i);
//Loesche aus der Liste
adapter.delete(i);
//TODO: Delete from DB or whatever
//Checken ob Liste leer
checkIsListEmpty();
}
}
}else{
MyToast.showShort(this, getString(R.string.hinweis_keine_selektion));
}
}
return super.onOptionsItemSelected(item);
}
Related
I have a Todo project in Android using a ListView. Each item of my listview have one switch in order to delete the task, one TextView and one ImageView. The problem is when I check a switch of a specific task, the task is deleted (desired behavior) but it checks the following one too (without deleting it) .
Here is the code of my Adapter:
public class Adapter extends BaseAdapter {
private List<Tache> lesTaches;
private Context context;
private LayoutInflater inflater;
public Adapter(Context context, List<Tache> list) {
this.context = context;
lesTaches = list;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return lesTaches.size();
}
#Override
public Object getItem(int position) {
return lesTaches.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null) {
view = (View) inflater.inflate(R.layout.tache_item, parent, false);
} else {
view = (View) convertView;
}
TextView intitule = (TextView) view.findViewById(R.id.intitule);
intitule.setText(lesTaches.get(position).getIntitule());
final Switch switch1 = (Switch) view.findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.isPressed()) {
if(isChecked) {
remove(lesTaches.get(position));
}
}
}
});
return view;
}
public void remove(Tache toDel) {
lesTaches.remove(toDel);
notifyDataSetChanged();
}
public void addItem(Tache toAdd) {
lesTaches.add(toAdd);
notifyDataSetChanged();
}}
And here is my tache_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:layout_marginHorizontal="5dp"
android:focusable="false" />
<TextView
android:id="#+id/intitule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/switch1"
android:layout_toRightOf="#+id/switch1" />
<ImageView
android:id="#+id/icon_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:layout_marginHorizontal="5dp"
app:srcCompat="#drawable/ic_info_black" />
</RelativeLayout>
Here is a screen of my app showing the problem (I deleted the first task so we do not see it but the second one get checked):
Image showing the problem:
I already search on the net and test to replace the setOnCheckedChangeListener by an onClickListener but the same problem appear.
i manage to do when i click the item in my listview , beside the column will show a tick over there, but now i have a problem in when i click on my item the tick will show but there is no function for my onitemclicklistener event. how to let this two function work in same time. sorry for my english, hope can understand
this is my setOnItemClickListener event
condimentlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView condimentitem =(TextView)view.findViewById(R.id.condcb);
String citem= condimentitem.getText().toString();
ArrayList<String> data = new ArrayList<String>();
data.add(citem);
String array[] = data.toArray(new String[0]);
for (int j = 0; j < array.length; j++) {
remark.append(String.valueOf(array[j]));
}
------condimentitem.setOnClickListener(new View.OnClickListener()-------
{
#Override
public void onClick(View v)
{
int visibility = btntick.getVisibility();
if(visibility == View.VISIBLE)
{
btntick.setVisibility(View.GONE);
}
else
{
btntick.setVisibility(View.VISIBLE);
}
}
});
}
});
this is my baseadapter to contor the tick
public class condimentlist extends BaseAdapter {
LayoutInflater mInflater;
private ArrayList<Integer> positions = new ArrayList<Integer>();
public ArrayList<Integer> getPositions() {
return positions;
}
public condimentlist() {
mInflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return CondimentList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.condimentlistview_details, null);
}
condcb = (TextView) convertView.findViewById(R.id.condcb);
final TextView tremark = (TextView) convertView.findViewById(R.id.Tremark);
btntick = (ImageView) convertView.findViewById(R.id.iv_tick);
Condiment myObj = CondimentList.get(position);
condcb.setText("" + myObj.getCondimentName());
-----------convertView.performClick ();------------------
return convertView;
}
condimentlistview_details.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/condcb"
android:text="Press"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="18sp" />
<ImageButton
android:layout_width="15dp"
android:layout_height="15dp"
android:background="#drawable/tick"
android:id="#+id/iv_tick"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp" />
</RelativeLayout>
I think problem is ImageButton in your listview Row xml file.
Put android:focusable="false" , and see it works!!!
<ImageButton
android:layout_width="15dp"
android:layout_height="15dp"
android:background="#drawable/tick"
android:id="#+id/iv_tick"
android:visibility="gone"
android:focusable="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp" />
Below is one of the question i answered before, you may need to create a list with one of the element of boolean as a flag. When you select, you turn that flag into true. Hope it helps.
enter link description here
You could define a static ArrayList in your activity class, then retrieve everything from that array list in the base adapter with a Hashmap. Then, you could use SetOnItemClickListener in your activity class to get the correct value of each row by referencing the activity's array list's position.
Works for me flawlessly. Let me know if you need example code.
Write this code inside BASE ADAPTER's getView()
condimentitem.setOnClickListener(new View.OnClickListener()-------
{
#Override
public void onClick(View v)
{
int visibility = btntick.getVisibility();
if(visibility == View.VISIBLE)
{
btntick.setVisibility(View.GONE);
}
else
{
btntick.setVisibility(View.VISIBLE);
}
}
});
Add convertView.performClick() inside condcb.OnClick method in adapter.
i have two spinners, say categories and subcategories. OnItemSelected of categories spinner i need to set the adapter for sub_categories spinner.I am able to set spinner for categories. But sub_categories spinner is creating trouble.
These arraylist are coming from servers, i made it static.
Looking into my code will give you proper idea that where i am mistaken.
This is my categories List:
public static ArrayList<String> categories=new ArrayList<String>();
public static ArrayAdapter<String> mArryAdtSpnnr;
and in the response.success, i am trying to do the following:
for(int i=0;i<mArray.length;i++){categories.add(mArray[i].getName());}
Here in this activity, where i need 2 spinners:
private void initializeWidgets() {
mspinner_categories=(Spinner)findViewById(R.id.spinner_categories);
mspinner_categories.setOnItemSelectedListener(this);
mspinner_subcategories=(Spinner)findViewById(R.id.spinner_subcategories);
ProfessionalListActivity.mArryAdtSpnnr = new ArrayAdapter<String>( EditProfileActivity.this,
android.R.layout.simple_spinner_item,ProfessionalListActivity.categories);
mspinner_categories.setAdapter(ProfessionalListActivity.mArryAdtSpnnr);
}
and on its item selected:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(EditProfileActivity.this,"Selected Item is: "+item,Toast.LENGTH_LONG).show();
// mspinner_subcategories.setSelection(position);
SubListProActivity.mArrySpnnr=new ArrayAdapter<String>
(EditProfileActivity.this,android.R.layout.simple_spinner_item,
SubListProActivity.subcategories);
mspinner_subcategories.setAdapter(SubListProActivity.mArrySpnnr);
}
I am setting second spinner adapter on click of first spinner. But nothing is displayed on this spinner. I did similar code to the other activity.
I am confused, this may be because in ProfessionalListActivity i am getting a category_id also, so that corresponding sublist gets opened. But in spinners i am adding it directly.
Edit:
Sublist class:
public static ArrayList<String> subcategories=new ArrayList<String>();
public static ArrayAdapter<String> mArrySpnnr;
in its response.success
for(int i=0;i<mArray.length;i++){
subcategories.add(mArray[i].getName());
}
Please help
This code approaches your problem as an ExpandableList and is from a working app. First is the listener for a button that calls the activity which:
displays a list of clickable first level options, which, when activated,
display drop down lists of clickable second-level options, when activated
display groups of 3 option radio buttons (only 1 selected button per radio group)
The original application is an (agri) inspection system - the user selects from groups of problems (1st level: insects, funghi, weeds), which problems are occuring (2nd level: insects[army worms, ladybugs, ants], funghi[stem rot, rust, mildew], weeds[common grass, african grass, morning glory]).
For each selected 2nd level option a radio button group to select the severity of problem pops up and the user must choose levels 1 (default), 2 OR 3.
Data is stored to be consumed elsewhere.
Calling the activity which displays a layout dedicated to INSPECTION, sending along the data that will populate the expandable lists.
private final OnClickListener btnDoneOnClick = new OnClickListener() {
public void onClick(View v) {
String input = areaName.getText().toString();
// english version
//String[] groupName = {"INSECTS", "WEEDS", "FUNGHI", "CLIMATE", "VARIOUS"};
String[] groupName = {"INSETOS", "ERVAS INVASORAS", "FUNGOS", "CLIMA", "VARIOS"};
String[][] childName = { { "Cigarrinha","Falsa medideira","Lagarta cartucho","Lagarta rosca","Percevejo (geral)"},
{ "Argentino","Buva","Capim colchao","Carrapicho","Corda viola","Falso Argentino","Leiteiro","Picao","Tiguera Milho","Tiguera Soja"},
{ "Antracnose","Cercospora","DFC","Ferrugem"},
{ "Erosao","Geada","Granizo","Incendio","Inundacao","Raio","Seca","Vento" },
{ "Furto","Fuga","Picada cobra" }
};
Intent intent00 = new Intent(getApplicationContext(), com.xxx.yyy.zzz.AgrInspectActivity.class);
intent00.putExtra("groupName", groupName);
int maxLength = 0;
for (int i=0;i<groupName.length;i++) {
intent00.putExtra(groupName[i], childName[i]);
maxLength = Math.max(childName[i].length, maxLength);
}
intent00.putExtra("arrayLength", maxLength);
// count childrenRows and put values in ARRAY
// to be used by CustomList to inflate layouts
// with proper number of lines
int[] countChild = new int[groupName.length];
for (int j=0;j<groupName.length;j++) {
countChild[j] = childName[j].length;
}
intent00.putExtra("countChild", countChild);
startActivity(intent00);
}
};
The activity proper:
public class AgrInspectActivity extends Activity {
ExpandableListAdapter mAdapter;
LayoutInflater mInflater;
int arrayLength;
String[] groups;
String[][] children;
int[][] array_output_data;
String[][] array_output_data_quantity;
int[] countChild;
public int[][] getArray_output_data() {
return array_output_data;
}
public String[][] getArray_output_data_quantity() {
return array_output_data_quantity;
}
int choice = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inspection);
ExpandableListView list = (ExpandableListView) findViewById(R.id.expandableListView1);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
groups = extras.getStringArray("groupName");
arrayLength = extras.getInt("arrayLength");
countChild = extras.getIntArray("countChild");
String[] tempArray = new String[arrayLength];
children = new String[groups.length][arrayLength];
for (int i=0;i<groups.length;i++) {
children[i] = extras.getStringArray(groups[i]);
// TODO delete this block debug ONLY
Log.i("data", groups[i]+groups.length+" get array loop "+i+" / "+ tempArray.length+"/ countChild: "+countChild[i]);
for (int j=0;j<children[i].length;j++) {
Log.d("data", j+" counter:temparray "+children[i][j]);
}
}
}
mAdapter = new InspectionMenu(this);
list.setAdapter(mAdapter);
}
public class InspectionMenu extends BaseExpandableListAdapter {
private Context myContext;
public InspectionMenu(Context context) {
myContext = context;
Log.i("data", "InspectionActivity InspectionMenu children length "+groups.length);
array_output_data = new int[groups.length][arrayLength];
array_output_data_quantity = new String[groups.length][arrayLength];
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(final int groupPosition,final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.inspection_row, null);
TextView childtext = (TextView) convertView.findViewById(R.id.textView1);
childtext.setText(children[groupPosition][childPosition]);
final RadioGroup rdg = (RadioGroup) convertView.findViewById(R.id.radioGroup1);
final RadioButton r1 = (RadioButton) convertView.findViewById(R.id.radio1);
final RadioButton r2 = (RadioButton) convertView.findViewById(R.id.radio2);
final RadioButton r3 = (RadioButton) convertView.findViewById(R.id.radio3);
final EditText inspectQuantity = (EditText) convertView.findViewById(R.id.inspection_quant);
if (array_output_data[groupPosition][childPosition] >0) {
//switch (Integer.parseInt(array_output_data[groupPosition][childPosition])) {
switch (array_output_data[groupPosition][childPosition]) {
case 1:
r1.setChecked(true);
break;
case 2:
r2.setChecked(true);
break;
case 3:
r3.setChecked(true);
break;
}
}
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
if (array_output_data[groupPosition][childPosition] > 0) {
cb.setChecked(true);
rdg.setVisibility(View.VISIBLE);
inspectQuantity.setVisibility(View.VISIBLE);
}
rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radio1) {
choice = 1;
} else if (checkedId == R.id.radio2) {
choice = 2;
} else if (checkedId == R.id.radio3) {
choice = 3;
} else {
Log.e("TGTG", "radio button selection invalid in InspectionActivityOld");
}
array_output_data[groupPosition][childPosition] = (choice);
}
});
cb.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked == true) { // display LEVEL (1,2,3) RADIO BUTTONS for this line
rdg.setVisibility(View.VISIBLE); // redundant?
try {
inspectQuantity.setVisibility(View.VISIBLE);
} catch (Exception except) {
Log.e("TGTG", "no open inspectQUantity "+except.getMessage()+" group "+groupPosition+" child "+childPosition);
}
r1.setChecked(true);
} else { // hide LEVEL RADIO BUTTONS for this line
rdg.setVisibility(View.GONE);
inspectQuantity.setVisibility(View.GONE);
rdg.clearCheck();
array_output_data[groupPosition][childPosition] = 0;
array_output_data_quantity[groupPosition][childPosition] = "";
}
}
});
if (array_output_data_quantity[groupPosition][childPosition] != null) {
inspectQuantity.setText(array_output_data_quantity[groupPosition][childPosition]);
}
try {
inspectQuantity.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
array_output_data_quantity[groupPosition][childPosition] = arg0.toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {}
});
} catch (Exception except) {
Log.e("TGTG", "did not add listener QUANTITY in inspection");
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return countChild[groupPosition];
}
#Override
public Object getGroup(int groupPosition) {
return null;
}
#Override
public int getGroupCount() {
return groups.length;
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group, null);
TextView grouptext = (TextView) convertView.findViewById(R.id.textView2);
grouptext.setText(groups[groupPosition]);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
These are the layout files:
group.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="64px"
android:text="TextView" android:textSize="40px" android:paddingLeft="100px" android:paddingTop="10px"/>
</LinearLayout>
inspection_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" android:id="#+id/ln">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_gravity="center_vertical"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="weeds"
android:textSize="20dip"
android:paddingLeft="20px"
android:gravity="center_vertical"/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-30px"
>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:orientation="horizontal" android:visibility="gone" android:layout_height="wrap_content" android:layout_marginLeft="72px" android:layout_marginBottom="-10px">
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false" android:visibility="visible" android:text="1"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:checked="false" android:visibility="visible" android:text="2"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:checked="false" android:visibility="visible" android:text="3"/>
</RadioGroup>
<EditText
android:id="#+id/inspection_quant"
android:visibility="gone"
android:layout_width="100px"
android:layout_height="wrap_content"
android:inputType="number"
android:layout_marginLeft="30px"
android:layout_marginBottom="-10px"/>
</LinearLayout>
</LinearLayout>
This should get your ball rolling in the correct direction.
I'm having trouble understanding how to use Intent to move list view elements. So I've made a separate project to practice this before actually figuring it out in my app. Basically, I want to have a "Favorites" activity that can be populated from something like a search results page. Instead of a search results page, I've just created a list view with some sample elements in them with a favorites button in each. I just need some guidance on how to go from there. Here is my code so far
MainActivity.java
public class MainActivity extends Activity {
private ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
generateList();
listView.setAdapter(new MyListAdapter(this, R.layout.item_view, data));
}
private void generateList() {
for (int i = 0; i < 5; i++) {
data.add("row/item " + i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyListAdapter extends ArrayAdapter<String> {
private int layout;
public MyListAdapter(Context context, int resource, List<String>
objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup
parent) {
ViewHolder minViewHolder = null;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView)
convertView.findViewById(R.id.list_item_text);
viewHolder.button = (Button)
convertView.findViewById(R.id.favorites_button);
viewHolder.button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "sent item " + position + "
to favorites tab", Toast.LENGTH_SHORT).show();
// data.remove(position);
MyListAdapter.this.notifyDataSetChanged();
}
});
convertView.setTag(viewHolder);
} else {
minViewHolder = (ViewHolder) convertView.getTag();
minViewHolder.title.setText(getItem(position));
}
return convertView;
}
}
public class ViewHolder{
TextView title;
Button button;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_centerHorizontal="true" /> </RelativeLayout>
item_view.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/list_item_text"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fav"
android:id="#+id/favorites_button"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I haven't set up a second activity because I wanted ideas on how to create a list that is empty but can be populated by that favorites button press. Any help at all is greatly appreciated!
Update arraylist according to favourite and call
adapter.notifyDataChanged();
if listview is same,
otherwise for different listview call another listview with adapter and new filtered arraylist
we want to create a list view using adapter and we want to set the properties of the the list item outside the adapter.
For instance ,the list view contains 200 rows and 14 column, then we need to create the list item using adapter.Here the objects in adapter is creating based on the which items shown in screen.
After creating adapter ,after outside adapter we want to put getter,setter for the item 198 means .If initially in device the items upto 10 is diplayed means then then 10 items objects is created in adapter but the remaining is created when user scroll down
So null pointer execption is arised for the item 198.
I want to create a ListView as a custom component.In that the user can add any number of rows,any number of columns,etc
Any items as a list view,etc.
My aim is to create library for list view .In that list view user can add any number of rows,any number of columns,any items textview,spinner,etc.I need suggestions how to achieve it
All are welcome to give their ideas.
try use:
your xml list file item.xml:
<LinearLayout>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tvDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text=""
android:textSize="20sp">
</TextView>
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="10dp"
android:text="">
</TextView>
</LinearLayout>
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher">
</ImageView>
<LinearLayout/>
And your class adapter
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
BoxAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
And your class for product
public class Product {
String name;
int price;
int image;
boolean box;
Product(String _describe, int _price, int _image, boolean _box) {
name = _describe;
price = _price;
image = _image;
box = _box;
}
}
And your main activity use the create adapter
boxAdapter = new BoxAdapter(this, products);
ArrayList<Product> products = new ArrayList<Product>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
...
//create adapter
fillData()
boxAdapter = new BoxAdapter(this, products);
// use lists
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
// data for adapter
void fillData() {
for (int i = 1; i <= 20; i++) {
products.add(new Product("Product " + i, i * 1000, R.drawable.ic_launcher, false));
}
What you need is to implement LazyListView.
And I think you have a nice tutorial here to start with.