I've created a custom listView which lists all installed apps on the device, in this list is the app icon, app name and a checkbox. I want to code the onCheckboxClicked method but I don't know where to place it, I've read it should be within the adapter but other examples i've been looking at have code within the main activity and I can't seem to get it working either way.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve currently installed apps
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities( mainIntent, 0);
List<AppDetails> appList = new ArrayList<>();
for (Object object : pkgAppsList)
{
ResolveInfo info = (ResolveInfo) object;
Drawable icon = getBaseContext().getPackageManager().getApplicationIcon(info.activityInfo.applicationInfo);
String strAppName = info.activityInfo.applicationInfo.publicSourceDir.toString();
String strPackageName = info.activityInfo.applicationInfo.packageName.toString();
final String title = (String)((info != null) ? getBaseContext().getPackageManager().getApplicationLabel(info.activityInfo.applicationInfo) : "???");
AppDetails tmp = new AppDetails(title, icon);
appList.add(tmp); //add title and icon into list
}
final ListView listview = (ListView) findViewById(R.id.listView);
final AppDetailsAdapter adapter = new AppDetailsAdapter(this, appList);
listview.setAdapter(adapter);
}
adapter:
public class AppDetailsAdapter extends BaseAdapter {
private List<AppDetails> data;
private Context context;
public AppDetailsAdapter(Context context, List<AppDetails> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.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) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
return view;
}
}
custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/icon"
android:layout_width="39dp"
android:layout_height="39dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:textSize="17sp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onCheckboxClicked"/>/>
</LinearLayout>
I've also read that the getView method needs to be modified to handle the checkbox but again I can't seem to do it with what I've tried so far
Replace your adapter's get view code with below code :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
checkBox .setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle your conditions here
}
});
return view;
}
here setOnCheckedChangeListener is method that you have to handle .
Related
I have a spinner and an adapter.
Spinner spinner = findViewById(R.id.spinner);
SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.spinner_item, getList());
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Log.e("PROGRAM", "Selected |" + position + "|");
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
This is my SpinnerAdapter dropdown creation
#Override
public View getDropDownView(final int position, final View convertView, final ViewGroup parent)
{
MyObject object = getItem(position);
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_object_item, parent, false);
((TextView) layout.findViewById(R.id.name)).setText(object.getName());
return layout;
}
And my_object_item xml is
<?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:id="#+id/item"
android:clickable="true"
android:focusable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"/>
</LinearLayout>
For some reason I can not get setOnItemSelectedListener to trigger. Should I be adding listener to every component of my_object_item and from there triggering setOnItemSelectedListener?
As you have suggested above, you can try to do things manually, by adding a listener that listens to clicks on either the TextView or ImageView (the components of each item in the spinner dropdown view), and then update the spinner view according to what was selected.
1) MainActivity.class:------------
public class MainActivity extends AppCompatActivity implements Listener {
private Spinner sp;
private SpinnerAdapter spinnerAdapter;
private String[] name = {
"N1",
"N2",
"N3",
"N4"
};
private int[] icon = {
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
sp = (Spinner) findViewById(R.id.sp);
spinnerAdapter = new SpinnerAdapter(getApplicationContext() , name , icon , name[0] , icon[0] , MainActivity.this); // TODO: Every time the activity (spinner) is created, the item selected is changed
//TODO to the initial name[0] and icon[0]. In order to solve this issue you can save the selected item (name and icon) value in sharedPreferences and use the saved value every time the spinner is opened.
sp.setAdapter(spinnerAdapter);
}
#Override
public void clicked(int position) {
if(spinnerAdapter != null){
spinnerAdapter.setCurrentNameIcon(name[position] , icon[position]);
}
}
2) SpinnerAdapter.class:---------------
public class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;
private String current_name;
private int current_icon;
private String[] name;
private int[] icon;
public SpinnerAdapter(#NonNull Context context , String[] name_ , int[] icon_ , String inital_name_ , int initial_icon_ , Listener l) {
mContext = context;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(l != null){
callback = l;
}
name = name_;
icon = icon_;
current_name = inital_name_;
current_icon = initial_icon_;
}
public int getCount() {
return name.length;
}
public Object getItem(int position) {
return name[position];
}
public long getItemId(int position) {
return position;
}
#NonNull
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final TextView tv;
ImageView iv;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.my_object_item, parent , false);
}
}
tv = (TextView) view.findViewById(R.id.name);
tv.setText(current_name);
iv = (ImageView) view.findViewById(R.id.icon);
iv.setBackground(mContext.getResources().getDrawable(current_icon));
return view;
}
#Override
public View getDropDownView(final int position, #Nullable View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
final TextView tv;
ImageView iv;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.my_object_item, parent , false);
}
}
tv = (TextView) view.findViewById(R.id.name);
tv.setText(name[position]);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null){
//https://stackoverflow.com/questions/7287195/android-spinner-close?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
View root = parent.getRootView();
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
callback.clicked(position);
}
}
});
iv = (ImageView) view.findViewById(R.id.icon);
iv.setBackground(mContext.getResources().getDrawable(icon[position]));
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null){
//https://stackoverflow.com/questions/7287195/android-spinner-close?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
View root = parent.getRootView();
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
callback.clicked(position);
}
}
});
return view;
}
public void setCurrentNameIcon(String name , int icon){
current_name = name;
current_icon = icon;
this.notifyDataSetChanged();
}
}
3) Listener interface:------------
public interface Listener {
public void clicked(int position);
}
4) main_activity.xml:---------
<?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">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sp">
</Spinner>
</android.support.constraint.ConstraintLayout>
5) my_object_item.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="60dp"
android:id="#+id/item"
android:clickable="true"
android:focusable="true">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/icon"
android:layout_gravity="center_vertical"
android:id="#+id/icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:gravity="center"
android:text="HI"
android:id="#+id/name"/>
</LinearLayout>
I have custom adapter for ListView. The ListView is in activity_main.xml and I have a ImageView in CustomAdapter layout which is populated with ListView using CustomAdapter.
My Question is I have to hide/show that image which is in custom layout with a button present in main layout. Like if there is 10 row in my ListView and 10 row have that image. I want to hide only for the particular row.
I hope you understand my question...Thanks in Advance
Here's my ListViewAdapter
public class ListViewAdapter extends ArrayAdapter<FileName> {
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context,int resource,List<FileName> filenames) {
super(context, resource, filenames);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
return view;
}
}
name = filenames.get(position).getName(); //getting the positin from listview
filenames.set(name,FileName.isVisible = true); //getting error on isVisible
I have writen a Sample code and tested
MainActivity
public class MainActivity extends AppCompatActivity {
List<FileName> filenames;
DBhelper dBhelper;dBhelper
SQLiteDatabase sqLiteDatabase;
ListViewAdapter listViewAdapter;
ListView listView;
ImageView lock;
String name;
//temporary button i have added
Button lockBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.lv_filename);
lockBTN = (Button) findViewById(R.id.lock);
filenames = getResult();
listViewAdapter = new ListViewAdapter(this, filenames);
listView.setAdapter(listViewAdapter);
lockBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//giving statically position is 2
int position = 2;
// when you press menu button or any other button
FileName fileName = filenames.get(position);
//here you can set true-Show and false-hide imageview
fileName.setVisible(true);
//and update the list
filenames.set(position, fileName);
listViewAdapter.notifyDataSetChanged();
}
});
}
//temporary data to show on listview
private List<FileName> getResult() {
List<FileName> fileNames = new ArrayList<>();
String[] nameArr = {"Name1", "Name2", "Name3"};
String[] shortTextArr = {"ShortText1", "ShortText2", "ShortText3"};
for(int i=0; i<nameArr.length;i ++){
FileName fileName = new FileName();
fileName.setName(nameArr[i]);
fileName.setShorttext(shortTextArr[i]);
//setting default is hide to imageview
fileName.setVisible(false);
fileNames.add(fileName);
}
return fileNames;
}
}
FileName
public class FileName {
private String name;
private String shorttext;
private boolean visible = true;
public String getName() {
return name;
}
public void setName(String _name) {
this.name = _name;
}
public String getShorttext() {
return shorttext;
}
public void setShorttext(String _shorttext) {
this.shorttext = _shorttext;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter{
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context, List<FileName> filenames) {
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filenames.size();
}
#Override
public Object getItem(int position) {
return filenames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
//holder.filename.setPaintFlags(holder.filename.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// check weather image is to show/hide
if (filenames.get(position).isVisible()) {
holder.imageView.setVisibility(View.VISIBLE);
} else {
holder.imageView.setVisibility(View.GONE);
}
return view;
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
}
activity_main.xml
<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"
android:padding="5dp"
android:orientation="vertical">
<ListView
android:id="#+id/lv_filename"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/lock"/>
<Button
android:id="#+id/lock"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Lock"/>
</RelativeLayout>
custom_list_item.xml
<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="1">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/utilities_notepad_icon" />
<LinearLayout
android:layout_width="232dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.77">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingTop="5dp"
android:text="Item Title"
android:textSize="16dp" />
<TextView
android:id="#+id/item_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="35"
android:paddingBottom="5dp"
android:paddingTop="1dp"
android:text="Item Description"
android:textColor="#999"
android:textSize="10dp" />
</LinearLayout>
<ImageView
android:id="#+id/lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/lo"
android:layout_marginTop="13sp" />
</LinearLayout>
Take a extra variable in your FileName class.
public class FileName {
public String name;
public String shortText;
public boolean visible = true; // Set the default value to true.
}
Now on external button click in your main layout, you might consider updating the list item accordingly. Just set the visible variable to false of that item you want to hide. Then call notifyDataSetChanged() on your adapter to reload the data.
And yes, in your adapter, just check the value of visible attribute and then decide to hide/show the ImageView. So the getView function of your adapter should look like this.
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// Hide/Show the ImageView
if (filenames.get(position).visible) holder.imageView.setVisibility(View.VISIBLE);
else holder.imageView.setVisibility(View.GONE);
return view;
}
I would suggest you to use RecyclerView instead of ListView. RecyclerView got more performance than the ListView. Now a days all are using RecyclerView instead of old ListView, it is quite easy to use as well.
And for handling your case create a function to remove the file name you wanted to remove in the RecyclerViewAdapter class as below
removeImageView(position){
fileNames.remove(position);
this.notifyItemRemoved(position);
}
notifyItemRemoved call will refresh the position in the recycler view and you will also get a nice view removing animation out of the box.
I have a listview that contains a set of a custom view. Inside each custom view is a gridview.
I want to be able to update the background of each cell in the gridview when the user clicks a checkbox in the custom view.
Here is my custom view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="32sp" />
<CheckBox
android:id="#+id/lblHeaderCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:layout_centerVertical="true" />
</RelativeLayout>
<ca.package.CustomGridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:gravity="center"
android:numColumns="7"
android:padding="10dp"
android:stretchMode="columnWidth"
clickable="true" />
Here is my layout for each grid cell
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:clickable="true" >
<TextView
android:id="#+id/grid_itemTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
</TextView>
</LinearLayout>
Here is how I fill the list
expListView = (ListView) this.findViewById(R.id.event_list);
prepareListData();
listAdapter = new CustomAdapter(this, listDataHeader,
listDataChild, listChildBoolean);
expListView.setAdapter(listAdapter);
Here is the getView method in my custom adapter for the listView
public View getView(int groupPosition, View convertView, ViewGroup parent) {
final int gp = groupPosition;
String headerTitle = (String) getGroup(groupPosition);
// Boolean bool = _listDataBoolean.get(groupPosition);
Boolean bool = currentCalendarEvents.get(groupPosition).getAlert();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
String[] data = new String[14];
List<String> times = _currentListDataChild.get(_currentListDataHeader
.get(groupPosition));
data[0] = "Su";
data[1] = "M";
data[2] = "Tu";
data[3] = "W";
data[4] = "Th";
data[5] = "F";
data[6] = "Sa";
data[7] = times.get(6); // sun
data[8] = times.get(0); // mon
data[9] = times.get(1); // tues
data[10] = times.get(2); // wed
data[11] = times.get(3); // thurs
data[12] = times.get(4); // fri
data[13] = times.get(5); // sat
ArrayList<Boolean> boolArray = _listChildBoolean.get(_currentListDataHeader
.get(groupPosition));
final GridView gridView = (GridView) convertView.findViewById(R.id.gridView);
final GridAdapter adapter = new GridAdapter(this._context, data, boolArray);
gridView.setAdapter(adapter);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
final CheckBox chk2 = (CheckBox) convertView
.findViewById(R.id.lblHeaderCheckbox);
chk2.setChecked(bool);
chk2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (chk2.isChecked()) {
currentCalendarEvents.get(gp).setAlert(true);
currentCalendarEvents.get(gp).setDaysTrue();
// I WANT TO UPDATE THE LIST HERE
Log.i(LOG_TAG, "box checked");
} else {
currentCalendarEvents.get(gp).setAlert(false);
currentCalendarEvents.get(gp).setDaysFalse();
// AND HERE
Log.i(LOG_TAG, "box not checked");
}
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "gridview clicked");
currentCalendarEvents.get(gp).setBoolDays(adapter.getHashMap());
}
});
return convertView;
}
Here is my GridAdapter
public class GridAdapter extends BaseAdapter {
private Context context;
private String[] items;
private ArrayList<Boolean> boolArray;
private ArrayList<View> views;
LayoutInflater inflater;
public GridAdapter(Context context, String[] items,
ArrayList<Boolean> boolArray) {
this.context = context;
this.items = items;
this.boolArray = boolArray;
this.views = new ArrayList<View>();
inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_cell, null);
final TextView tv = (TextView) convertView
.findViewById(R.id.grid_itemTxt);
tv.setText(items[position]);
if (position < 7) {
convertView.setBackgroundColor(Color.DKGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
tv.setTextColor(Color.WHITE);
tv.setTypeface(null, Typeface.BOLD);
tv.setLines(2);
} else {
Log.e("blerp", "test : " + items[position]);
if (!items[position].equals("")) {
if (boolArray.get(position % 7)) {
convertView.setBackgroundColor(context.getResources()
.getColor(R.color.LightGreen));
} else {
convertView.setBackgroundColor(Color.LTGRAY);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolArray.get(position % 7)) {
((View) tv.getParent())
.setBackgroundColor(Color.LTGRAY);
boolArray.set(position % 7, false);
} else {
((View) tv.getParent())
.setBackgroundColor(context
.getResources().getColor(
R.color.LightGreen));
boolArray.set(position % 7, true);
}
}
});
} else
convertView.setBackgroundColor(Color.LTGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tv.setLines(2);
}
}
return convertView;
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return position;
}
public HashMap<String,Boolean> getHashMap() {
HashMap<String, Boolean> hm = new HashMap<String,Boolean>();
hm.put("sun", boolArray.get(0));
hm.put("mon", boolArray.get(1));
hm.put("tues", boolArray.get(2));
hm.put("wed", boolArray.get(3));
hm.put("thurs", boolArray.get(4));
hm.put("fri", boolArray.get(5));
hm.put("sat", boolArray.get(6));
return hm;
}
}
Any help would be greatly appreciated, I can post more of my code if need be.
initiate gridview and checkbox in the adapter class (using find view by id).
then pass
if (checkBox.isChecked) {
gridview.setBackgroundColor(Color.rgb(x,y,z)))}
I have List view with custom adapter and I have problem with removing items from list. Here is definition of list row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:descendantFocusability="blocksDescendants">
<CheckBox
android:id="#+id/history_list_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/history_list_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/history_list_check"/>
<ImageView
android:id="#+id/history_list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/history_drunk_image_description"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
My custom adapter:
public class HistoryArrayAdapter extends ArrayAdapter<Measure> {
private final List<HistoryRowModel> list;
private final Activity context;
public HistoryArrayAdapter(Activity context, List<Measure> list) {
super(context, R.layout.history_list_row, list);
this.context = context;
this.list = new ArrayList<HistoryRowModel>();
for(Measure measure : list) {
HistoryRowModel rowModel = new HistoryRowModel(measure);
this.list.add(rowModel);
}
}
static class ViewHolder {
protected CheckBox checkbox;
protected TextView text;
protected ImageView imageView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.history_list_row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.history_list_check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
HistoryRowModel element = (HistoryRowModel) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
viewHolder.text = (TextView) view.findViewById(R.id.history_list_label);
viewHolder.imageView = (ImageView) view.findViewById(R.id.history_list_image);
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());
HistoryRowModel rowModel = list.get(position);
Measure measure = rowModel.getMeasure();
long time = measure.getTimestamp();
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
holder.text.setText(dateFormat.format(time));
int resource = getImage(measure.getThreshold());
if(resource == -1)
{
holder.imageView.setImageResource(R.drawable.unknown);
}
else
{
holder.imageView.setImageResource(resource);
}
return view;
}
}
And here is my remove from list code:
private void removeSelectedRows() {
View v;
CheckBox cb;
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
cb = (CheckBox) v.findViewById(R.id.history_list_check);
if(cb.isChecked())
{
removeMeasure(i);
}
}
}
private void removeMeasure(long rowId) {
Measure toRemove = adapter.getItem((int)rowId);
try {
Dao<Measure, Integer> measureDao = databaseHelper.getMeasureDao();
DeleteBuilder<Measure, Integer> db = measureDao.deleteBuilder();
db.where().eq("id", toRemove.getId());
measureDao.delete(db.prepare());
}
catch(Exception e) {
e.printStackTrace();
}
adapter.remove(toRemove);
}
My problem is that when I check some item and then invoke removeSelectedRows its remove always last item from list. Then when I return from this activity and go back again it's turn out that the proper row was delete from database and list show proper list rows. So it's looks like line
adapter.remove(toRemove);
remove wrong item from adapter. Any idea what is wrong with this code?
SOLVED
njzk2 was right in his comment
Replace all your adapter calls with list.getAdapter() calls. Or at least show us how you initialize the adapter variable.
EDIT: The notifyOnChange flag is 'true' by default so calling any of the following adapter methods will invoke the notifyDataSetChanged() method of the same object: add(T), insert(T), remove(T), clear()
I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}