I need to add onClick to the child items in ExpandableListView. I have reviewed other posts regarding this, but I could not integrate the code into mine, possibly due to a different variation of ExpandableListView codes.
It would be great if you can provide some in code explanation as well. Many thanks.
Here are my source codes:
activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ExpandableListView
android:id="#+id/expLV"
android:layout_width="match_parent"
android:layout_height="match_parent"></ExpandableListView>
</RelativeLayout>`
list_parent.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="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/listP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="20dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
/>
</LinearLayout>
list_child.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:id="#+id/listC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredChildPaddingLeft"
android:textSize="14dp"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
</LinearLayout>
ExpandableListAdapter.java
package com.example.ehsan.myexplistview;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String, List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}
#Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}
#Override
public Object getChild(int i, int i1) {
return listHashMap.get(listDataHeader.get(i)).get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
String parentText = (String)getGroup(i);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_parent, null);
}
TextView listP = (TextView)view.findViewById(R.id.listP);
listP.setTypeface(null, Typeface.BOLD);
listP.setText(parentText);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
final String childText = (String)getChild(i,i1);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_child, null);
}
TextView listC = (TextView)view.findViewById(R.id.listC);
listC.setText(childText);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(i1==0){
Intent intent = new Intent(activity,OneTwoThree.class);
activity.startActivity(intent);
}
else if (i1 ==1){
Intent intent = new Intent(activity,FourFiveSix.class);
activity.startActivity(intent);
}
else if (i1 ==2){
Intent intent = new Intent(activity,SevenEightNine.class);
activity.startActivity(intent);}
else if (i1 ==3){
Intent intent = new Intent(activity,TenElevenTwelve.class);
activity.startActivity(intent);}
}
});
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity.java
package com.example.ehsan.myexplistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private ExpandableListAdapter expandableListAdapter;
private List<String> listP;
private HashMap<String, List<String>> listC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = (ExpandableListView)findViewById(R.id.expLV);
initData();
expandableListAdapter = new ExpandableListAdapter(this, listP, listC);
expandableListView.setAdapter(expandableListAdapter);
}
private void initData(){
listP = new ArrayList<>();
listC = new HashMap<>();
listP.add("ABC");
listP.add("DEF");
listP.add("GHI");
listP.add("JKL");
List <String> abc = new ArrayList<>();
abc.add("123");
List <String> def = new ArrayList<>();
def.add("456");
def.add("789");
List <String> ghi = new ArrayList<>();
ghi.add("101112");
ghi.add("131415");
ghi.add("161718");
List <String> jkl = new ArrayList<>();
jkl.add("192021");
jkl.add("222324");
jkl.add("252627");
jkl.add("282930");
listC.put(listP.get(0),abc);
listC.put(listP.get(1),def);
listC.put(listP.get(2),ghi);
listC.put(listP.get(3),jkl);
}
}
You can set child click of expandable list in two ways
1.write child click event inside the getChildView() method.
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Page page =(Page) getChild(groupPosition, childPosition);
convertView = inflater.inflate(R.layout.child_list_layout, null);
Button mButton=(Button)convertView.findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Your code goes here ....
}
});
return convertView;
}
2.write click directly from expandable listview.
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(
ExpandableListView parent, View v,
int groupPosition, int childPosition,
long id) {
GoCategory(mainMenusList.get(groupPosition)
.getPagesList().get(childPosition));
return false;
}
});
Related
im new to android development and i have managed to develop an application with a listview of name, phone number and district, which is searchable and it is working really well. im using positions to click and take me to the dial pad, but the problem is, if an item is searched, it does not mantain its position given to it initially. what i want when a user searches for a name or district, it opens in the dial pad with a number written there.
Here is my contacts.java
public class Contacts extends AppCompatActivity {
ListView listView;
String[] name = {"Achibu john peter - Serere - 0772698033", "Agaba - Amon - Rukiga -
0782090694\n", "Agaja joseph - kaberamaido - 0775004193/0752451894\n",}
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("DFO Contacts");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0){
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel: +256772698033"));
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search for your DFO");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
and menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search_view"
android:title="Search"
app:showAsAction="always"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
/>
</menu>
And the activity_contacts
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".Contacts">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#D4AC0D"
app:subtitleTextColor="#0A0A0A"
app:titleTextColor="#111111"
/>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/poppinsmedium"
android:textSize="20sp"
android:layout_marginLeft="15dp"
android:clickable="true"
/>
</LinearLayout>
You need to use custom Array Adapter with custom Layout with a TextView and add OnClickListener for each TextView.
I've changed your code to make it work.
contacts.java
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class Contacts extends AppCompatActivity {
ListView listView;
List<String> name;
CustomAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set Toolbar & title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("DFO Contacts");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
listView = findViewById(R.id.listview);
// Creating List<String> from valus
name = new ArrayList<>();
name.add("Achibu john peter - Serere - 0772698033");
name.add("Agaba - Amon - Rukiga - 0782090694");
name.add("Agaja joseph - kaberamaido - 0775004193");
arrayAdapter = new CustomAdapter(name, this);
listView.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem menuItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search for your DFO");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
arrayAdapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
CustomAdapter.java
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final int mResource;
private Context mContext;
private List<String> orig;
private List<String> dataSet;
private int selectedPosition;
public CustomAdapter(List<String> data, Context context) {
super(context, android.R.layout.simple_list_item_1, data);
mContext = context;
// We need to make backup of original list
dataSet = data;
orig = data;
// Store for later use
mInflater = LayoutInflater.from(context);
mResource = android.R.layout.simple_list_item_1;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return createItemView(position, convertView, parent);
}
private View createItemView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mInflater.inflate(mResource, parent, false);
viewHolder.txtName = convertView.findViewById(android.R.id.text1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String item = getItem(position);
viewHolder.txtName.setText(item);
// Here we will try to extract phone number from current item
// it looks like xxxxx - xxxxx - 1234567890
// or like xxxxx - xxxxx -xxxxxx - 1234567890
// we need to extract 1234567890 here
// we will split by "-" & last one in array will be the phone number
// you may try another way to get so
String[] s = item.split("-");
String p = s[s.length-1].trim(); // Extracted Phone Number
viewHolder.txtName.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel: " + p));
mContext.startActivity(intent);
});
return convertView;
}
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<String> results = new ArrayList<String>();
if (orig == null)
orig = dataSet;
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final String g : orig) {
if (g.toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
dataSet = (List<String>) results.values;
notifyDataSetChanged();
}
};
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public String getItem(int position) {
return dataSet.get(position);
}
}
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search_view"
android:icon="?android:attr/actionModeWebSearchDrawable"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always" />
</menu>
and activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="15dp"
android:clickable="true"
android:textSize="20sp"
tools:listitem="#android:layout/simple_list_item_1"
android:focusable="true" />
</LinearLayout>
Hope it will help.
I created a ListView and a custom adapter to use with the list view. For some reason, if I add more than one item to the list, it does show several items, but all of them are identical to the first one.
At first I used a layout file to create each item but then I gave up and dynamically created a text view just to test it. It didn't work in both ways.
List with same item
Here is my code:
ArtistAdapter.java
package com.example.list2;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ArtistAdapter extends BaseAdapter
{
private ArrayList<String> artists;
private Context context;
private LayoutInflater inflater;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
this.inflater = LayoutInflater.from(context);
}
public ArtistAdapter(Context context)
{
this(context, new ArrayList<String>());
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
//LayoutInflater li = ((Activity)context).getLayoutInflater();
//v = inflater.inflate(R.layout.item,viewGroup,false);
//((TextView)v.findViewById(R.id.name)).setText((String)getItem(i));
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
public void add(String name)
{
artists.add(name);
notifyDataSetChanged();
}
}
MainActivity.java
package com.example.list2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
//ArrayAdapter<String> aa;
ArtistAdapter aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
//aa = new ArrayAdapter<String>(this,R.layout.item,new ArrayList<String>());
aa = new ArtistAdapter(this);
l.setAdapter(aa);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
aa.add(inp);
//aa.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/input"
android:hint="Something..."
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/submit"
android:text="Submit!"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"
android:animateLayoutChanges="true"
></ListView>
</LinearLayout>
Do you need to use a custom Adapter? Otherwise this code works well using ArrayAdapter:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArrayAdapter<String> artistAdapter;
List<String> listItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArrayAdapter<String>(this,R.layout.item, R.id.textView,listItems);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
listItems.add(inp);
artistAdapter.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
You need to update the arraylist and then set the adapter. For some reason notify adapter is not working. Here's the solution:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArtistAdapter artistAdapter;
ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArtistAdapter(this, arrayList);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
arrayList.add(inp);
l.setAdapter(artistAdapter);
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
====
public class ArtistAdapter extends BaseAdapter
{
private ArrayList artists;
private Context context;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
}
We are developing an Android application which creates plans and schedules. I have an ExpandableListView and I need to add deleting buttons where the user can delete a specific schedule or the complete plan. The Schedule item is the Child of the Plan item.
I was developing deleting the schedule part first. I thought that each child item can include one text view and the deleting button. This is the schedule_group.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.8">
<TextView
android:id="#+id/scheduleGroup"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textColor="#android:color/black" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2">
<ImageButton
android:id="#+id/scheduleDeleteBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:srcCompat="#drawable/delete_icon"
android:clickable="true"
></ImageButton>
</LinearLayout>
</LinearLayout>
And here is the PlansFragment.java where I create and delete the plans and the schedules.
package com.example.easyplan;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class PlansFragment extends Fragment {
MainAdapter mainAdapter;
ExpandableListView planExplandable;
List<String> listPlanName;
HashMap<String, List<String>> listSchedules;
ImageButton scheduleDeleteBtn;
TextView textView;
static int count = 0;
View view;
public PlansFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_plans_fragment, container, false);
listPlanName = new ArrayList<String>();
listSchedules = new HashMap<String, List<String>>();
scheduleDeleteBtn = view.findViewById(R.id.scheduleDeleteBtn);
scheduleDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSchedule();
}
});
// get the listview
planExplandable = (ExpandableListView) view.findViewById(R.id.plansExpandable);
textView = view.findViewById(R.id.scheduleGroup);
createAPlan(3);
createAPlan(1);
createAPlan(3);
createAPlan(4);
mainAdapter = new MainAdapter(getActivity(), listPlanName, listSchedules);
// setting list adapter
planExplandable.setAdapter(mainAdapter);
return view;
}
The problem is here:
private void deleteSchedule() {
}
private void createAPlan(int sch){
listPlanName.add("Plan#"+(count+1));
List<String> schedules = new ArrayList<String>();
if(sch > 0 ){
for (int i = 1; i <= sch; i++){
schedules.add("Schedule#" + i);
}
}
listSchedules.put(listPlanName.get(count),schedules);
count++;
}
}
I'm not sure how to access the child item via the button. If you could help that would be great! Thank you.
I added the remove part under getChildView() method. If anyone needs a similar solution:
package com.example.easyplan;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class MainAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> listPlan; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> listScheduleMap;
ImageButton scheduleDeleteBtn;
public MainAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.listPlan = listDataHeader;
this.listScheduleMap = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.schedule_group, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.scheduleGroup);
scheduleDeleteBtn = convertView.findViewById(R.id.scheduleDeleteBtn);
scheduleDeleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> plan = listScheduleMap.get(listPlan.get(groupPosition));
plan.remove(childPosition);
notifyDataSetChanged();
}
});
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.listScheduleMap.get(this.listPlan.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.listPlan.get(groupPosition);
}
#Override
public int getGroupCount() {
return this.listPlan.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.plan_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.planGroup);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
I have a RecyclerView that gets inflated in a Fragment. The problem is, when the items count gets more than views height, every item that is in the view will get a width of highest content (I mean all will get wrap content of highest width). In the image it's more specific, also after scrolling those views that will get refreshed will have a correct width (match parent). I already have tried those code suggestions on other questions but still problem exists. here is my code:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
The xml layout for items:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
android:layout_margin="5dp"
android:id="#+id/baseBg"
android:orientation="vertical">
<LinearLayout
android:id="#+id/expand_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_background"
android:foreground="?selectableItemBackground"
android:gravity="center|right"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="#color/colorPage5"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Code snippet that does the fragment replace:
mainPageFrameLayout.removeAllViews();
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainPageFrameLayout, new MojtamaFragment(id, "3"));
ft.commit();
And the mainPageFrameLayout:
<FrameLayout
android:id="#+id/mainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:animateLayoutChanges="true"
android:background="#color/colorPage5" />
The adapter and the onCreateView:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
...
//(this part items is getting generated by a Http Request)
...
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
return rootView;
}
Images:
Edit: Image explanation: as you can see in image 1 when items numbers gets more than views height items width gets wrap_content instead of match_parent (Image 2 is the correct one that it should be) in image 3 as you can see after i did scroll, items that get's re-instantiated gets correct width. I hope you get the point.
Edit 3: This is whole adapter and viewholder code and imports:
package com.ahrabi.ojekavir.Fragments;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.ahrabi.ojekavir.R;
import com.ahrabi.ojekavir.connector.HttpVolley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Ahrabi2 on 1/10/2018.
*/
#SuppressLint("ValidFragment")
public class MojtamaFragment extends Fragment {
public static final String GET_COMPLEX_LIST_URL = "/Building/getComplexList";
public static final String LOGIN_URL = "/user/Login";
SharedPreferences prefs;
public String firsturl;
private String[] id, title;
private String idCame, complexID;
#SuppressLint("ValidFragment")
public MojtamaFragment(String id, String complexID) {
this.idCame = id;
this.complexID = complexID;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs.getBoolean("net_switch", false)) {
// Your switch is on
Log.v("Requests", "Over Network");
firsturl = prefs.getString("internet_url", getResources().getString(R.string.pref_default_display_internet));
Log.v("Over internet url", firsturl);
} else {
// Your switch is off
Log.v("Requests", "Over Local");
firsturl = prefs.getString("local_url", getResources().getString(R.string.pref_default_display_local));
Log.v("Local url", firsturl);
}
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "ComplexTypeId";
keys[1] = "regionID";
values[0] = complexID;
values[1] = idCame;
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + GET_COMPLEX_LIST_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("-7")) {
} else {
// response = response.replaceAll("\\", "");
Log.v("Response", response);
String jsonResult = "{" + "\"" + "android" + "\"" + ":" + response
+ "}";
try {
JSONObject jObject = new JSONObject(jsonResult);
// Getting JSON Array from URL
JSONArray android = jObject.getJSONArray("android");
Log.v("android", android.toString());
Log.v("android.length()", "" + android.length());
id = new String[android.length()];
title = new String[android.length()];
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
id[i] = c.getString("id");
title[i] = c.getString("Name");
}
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return rootView;
}
private void showLoginPopup(String page) {
LayoutInflater curInflate = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View curLayout = curInflate.inflate(R.layout.login_popup,
(ViewGroup) getActivity().findViewById(R.id.mainLinearPopup));
final PopupWindow swindo = new PopupWindow(curLayout,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
swindo.setBackgroundDrawable(new BitmapDrawable());
swindo.setFocusable(true);
// swindo.setAnimationStyle(R.style.PopupWindowAnimation);
swindo.showAtLocation(curLayout, Gravity.BOTTOM,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout bg = (LinearLayout) curLayout
.findViewById(R.id.bgLinearPopup);
LinearLayout loginIV = (LinearLayout) curLayout
.findViewById(R.id.loginIV);
final EditText loginUserName = (EditText) curLayout
.findViewById(R.id.loginUserName);
final EditText loginPassword = (EditText) curLayout
.findViewById(R.id.loginPassword);
if (page.contentEquals("1"))
loginIV.setBackgroundResource(R.drawable.item_brown_bg);
else if (page.contentEquals("3"))
loginIV.setBackgroundResource(R.drawable.item_orange_bg);
bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
swindo.dismiss();
}
});
loginIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (loginUserName.getText().toString().contentEquals("")){
} else if (loginPassword.getText().toString().contentEquals("")){
} else {
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "userName";
keys[1] = "password";
values[0] = loginUserName.getText().toString();
values[1] = loginPassword.getText().toString();
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + LOGIN_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("1")) {
} else {
}
}
});
}
}
});
}
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private RecyclerView recyclerView;
private String[] id, title;
private Context context;
private String complexID;
private MojtamaFragment mojtamaFragment;
public SimpleAdapter(RecyclerView recyclerView, String[] id, String[] title, Context context, String complexID,MojtamaFragment mojtamaFragment) {
this.recyclerView = recyclerView;
this.id = id;
this.title = title;
this.context = context;
this.complexID = complexID;
this.mojtamaFragment = mojtamaFragment;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textViewTitle.setText(title[position]);
if (complexID.contentEquals("1"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage6));
else if (complexID.contentEquals("3"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage5));
}
#Override
public int getItemCount() {
return id.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewTitle;
private LinearLayout expandButton;
public ViewHolder(View itemView) {
super(itemView);
expandButton = itemView.findViewById(R.id.expand_button);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
expandButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(getAdapterPosition());
mojtamaFragment.showLoginPopup(complexID);
}
}
}
}
After so much editing and experiencing i found a part of code from my xml layout (the one that FrameLayout is in it and fragment gets replaced by it) has something to do with error:
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.ahrabi.ojekavir.CityActivity"
tools:showIn="#layout/activity_city">
after removing app:layout_behavior and changing ContraintLayout to some Linear or RelativeLayout problem now is gone.
I don't know why this part raises such problem, but it has definitely a reason.
This activity consists of typing an ingredient (then showing it) and check a checkbox next to it. I have the following bugs that I can't get rid of (I've been searching for 5 hours for a solution):
If I press back so the keyboard hides,when I click on the search view,it never shows again but for going to the home screen and entering back again.
If I check a checkbox and scroll,there will be other checkboxes randomly checked.
How can I put in an array the ingredients that I have checked and send that array to the next activity?(activity_ingredient list)
Here is the code:
package ro.mosgoreanu.andu.foodholic;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.Arrays;
public class typing_window extends AppCompatActivity implements view.OnClickListener {
private static Button button;
String[] items;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
});
}
public void buttononClick()
{
startActivity(new Intent("ro.mosgoreanu.andu.foodholic.ingredient_list"));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
buttononClick();
break;
}
}
public void searchItem(String textToSearch){
for(String item:items) {
if(!item.contains(textToSearch)){
listItems.remove(item);
}
}
adapter.notifyDataSetChanged();
}
public void initList(){
items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry","chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise","milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)","potato (white)","soy sauce","tomato","yogurt"};
listItems = new ArrayList<>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txt, listItems );
listView.setAdapter(adapter);
}
}
and the xml for the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="ro.mosgoreanu.andu.foodholic.typing_window"
android:background="#89913f">
<include layout="#layout/content_typing_window" />
<EditText
android:id="#+id/txtsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search Ingredient"
android:textAlignment="textStart"
android:paddingLeft="50dp"
android:layout_toLeftOf="#+id/imageButton"
android:layout_toStartOf="#+id/imageButton"
android:allowUndo="true" />
<SearchView
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingEnd="0dp"
android:paddingLeft="0dp"
android:translationY="-5dp"
android:focusable="true"
android:clickable="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View list"
android:id="#+id/button"
android:layout_marginRight="26dp"
android:layout_marginEnd="26dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#00ffffff"
android:translationX="280dp"
android:translationY="-2dp"
android:clickable="true"
android:allowUndo="true" />
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:foregroundTint="#ffffff"
android:paddingTop="50dp" />
</android.support.design.widget.CoordinatorLayout>
and the layout 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">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="19dp"
android:text="Add"
android:id="#+id/checkBox"
android:layout_gravity="right"
android:translationY="25dp"
android:translationX="0dp"
android:layout_marginLeft="280dp"
android:focusable="false"/>
<TextView
android:id="#+id/txt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
/>
</LinearLayout>
Hey i have done one with using ArrayAdapter and SearchViewHolder
Check it and Provide any Response.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static Button button;
String[] items;
private Fruits[] itemss;
ArrayList<String> listItems;
ArrayAdapter<Fruits> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruits it = adapter.getItem(position);
it.toggleChecked();
SelectViewHolder viewHolder = (SelectViewHolder) view.getTag();
viewHolder.getCheckBox().setChecked(it.isChecked());
}
});
}
private void initList() {
itemss = (Fruits[]) getLastNonConfigurationInstance();
ArrayList<Fruits> items = new ArrayList<Fruits>();
items.add(new Fruits("breadcumb"));
items.add(new Fruits("butter"));
items.add(new Fruits("capiscum"));
items.add(new Fruits("carrot"));
items.add(new Fruits("cheese"));
items.add(new Fruits("cherry"));
items.add(new Fruits("chicken cutlets"));
items.add(new Fruits("cucumber"));
items.add(new Fruits("egg"));
items.add(new Fruits("flour"));
items.add(new Fruits("garlic"));
items.add(new Fruits("ham"));
items.add(new Fruits("lemon juice"));
items.add(new Fruits("mayonnaise"));
items.add(new Fruits("milk"));
items.add(new Fruits("mushroom"));
items.add(new Fruits("onion (red)"));
items.add(new Fruits("onion (white)"));
items.add(new Fruits("peas"));
items.add(new Fruits("pepper"));
items.add(new Fruits("pork"));
items.add(new Fruits("pickles"));
items.add(new Fruits("potato (red)"));
items.add(new Fruits("potato (white)"));
items.add(new Fruits("soy sauce"));
items.add(new Fruits("tomato"));
items.add(new Fruits("yogurt"));
adapter = new ActivityAdapter(this, items);
listView.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private static class Fruits {
private String name = "";
private boolean checked = false;
public Fruits() {
}
public Fruits(String name) {
this.name = name;
}
public Fruits(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
private static class SelectViewHolder {
private CheckBox checkBox;
private TextView textView;
public SelectViewHolder() {
}
public SelectViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
private static class ActivityAdapter extends ArrayAdapter<Fruits>{
private LayoutInflater inflater;
public ActivityAdapter(Context context, List<Fruits> list) {
super(context, R.layout.content_typing_window, R.id.txt, list);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruits fruit = (Fruits) this.getItem(position);
CheckBox checkBox;
TextView textView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.content_typing_window, null);
textView = (TextView) convertView
.findViewById(R.id.txt);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(new SelectViewHolder(textView, checkBox));
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Fruits li = (Fruits) cb.getTag();
li.setChecked(cb.isChecked());
}
});
}
else {
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
checkBox.setTag(fruit);
checkBox.setChecked(fruit.isChecked());
textView.setText(fruit.getName());
return convertView;
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
break;
}
}
// public void initList(){
// items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry"
// ,"chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise",
// "milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)",
// "potato (white)","soy sauce","tomato","yogurt"};
// listItems = new ArrayList<>(Arrays.asList(items));
// adapter = new ArrayAdapter<mItems>(this, R.layout.content_typing_window, R.id.txt, listItems );
// listView.setAdapter(adapter);
// }
#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_main, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}