What I am trying to accomplish is to have a checkbox in each row, having the ability to check the box separately (for batch deleting) and being able to select the entire row to view data associated with the list item.
I have done a checkbox with a textview but that only lets be select the box and I cant click on the list item to view that items data. I also used checkedTextView but that checks the box where ever you click on the row calling the onListItemClick and thats not what I want either. Is there some what I can separate checking the box from clicking a listview item?
Pretty much trying to do what the gmail app does when selecting messages to delete and view
this is my row layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/nameCheckTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:paddingTop="5dp"
android:paddingLeft="15dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
creating listview
#Override
public void onActivityCreated(Bundle state){
super.onActivityCreated(state);
lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setItemsCanFocus(false);
setEmptyText("No Bowlers");
registerForContextMenu(getListView());
populateList();
}
EDIT:
my populate method
public void populateList(){
String[] fields = new String[] {BowlersDB.NAME};
//mAdapter = new CheckAdapter(getActivity(),R.layout.check_listview,null,fields,new int[] {R.id.nameCheckTV});
mAdapter = new SimpleCursorAdapter(getActivity(),R.layout.check_listview,null,fields,
new int[] {R.id.nameCheckTV});
setListAdapter(mAdapter);
getLoaderManager().initLoader(0,null,this);
}
The issue is that Android doesn't allow you to select list items that have elements on them that are focusable. Try modifying the checkbox on the list item:
android:focusable="false"
I had a strange workaround with this issue. Here is my solution.
Use this for your ListView. Product is just a model object to hold your data in this case:
public class CatalogItemAdapter extends ArrayAdapter<Product> //
{
private ArrayList<Product> products;
private Activity activity;
public CatalogItemAdapter(Context context, int textViewResourceId,
ArrayList<Product> items, Activity activity) //
{
super(context, textViewResourceId, items);
this.products = items;
this.activity = activity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) //
{
Product product = products.get(position);
if (convertView == null) //
{
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.catalog_item_stub, null, false);
}
}
}
Somewhere in your onResume(), put this:
listView = (ListView) activity.findViewById(R.id.CatalogProducts);
m_adapter = new CatalogItemAdapter(activity,
R.layout.catalog_item_stub, products, activity);
if (products == null)
products = new ArrayList<Product>();
listView.setAdapter(m_adapter);
R.layout.catalog_item_stub is a layout stub created in XML like so (put the appropriate items in it for you, like the checkbox):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="#+id/catalog_item_stub"
android:layout_width="match_parent" android:layout_height="90dp"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dp">
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent" android:weightSum="5"
android:gravity="center_vertical|right">
<TextView android:layout_width="0dp" android:layout_height="match_parent"
android:text="product_title" android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/ProductTitle" android:padding="5dp"
android:layout_weight="2.5" android:textColor="#000000" />
<CheckBox android:padding="5dp" android:layout_height="match_parent"
android:text="select" android:layout_width="0dp" android:id="#+id/chkSelect"
android:layout_weight="1.5" android:textColor="#000000"
android:gravity="right" />
</LinearLayout>
Hopefully this helps! Holler if you need any clarification.
The gmail app uses its own view called CanvasConversationHeaderView that manages its subviews. This method is probably more heavy-weight than what you are looking for.
An easier method would be to make the checkbox not "focusable" (as Alex Lockwood suggests) and then attach an onClick in the XML.
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:focusable="false"
android:onClick="onCheckboxClicked"/>
Then in your activity code add
public void onCheckboxClicked(View view) {
RelativeLayout rl = (RelativeLayout)view.getParent();
Log.d(TAG, "Checkbox clicked! getTag returned: " + rl.getTag());
}
EDIT: How to add a tag from SimpleCursorAdapter.bindView
private class MyCursorAdapter extends SimpleCursorAdapter {
public MyCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//Log.d(TAG, "Cursor pos: " + cursor.getPosition());
String name = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
view.setTag(name);
super.bindView(view, context, cursor);
}
}
Note: I set the tag to the View from the bindView call, which is the RelativeLayout at the root of your xml. Look at the onCheckboxClicked method to see how I got the tag.
You need to set an onItemClickListener for your ListView that will start another activity with the info of the row selected when the row is clicked (outside the CheckBox of course). I would recommend having your Activity implement AdapterView.OnItemClickListener which requires the method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
Inside this method you can launch an Activity with details corresponding to the data in the row selected.
Hopefully I understood your question correctly.
Related
I just started learning Android and I am trying to create a simple view where a portion of the main XML is a listview.
Here is my main.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">
<RelativeLayout
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="#+id/Menu">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/menu_item_1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="129dp" />
</RelativeLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_toEndOf="#+id/Menu"
android:layout_toRightOf="#+id/Menu"
android:layout_alignParentTop="true"
android:id="#+id/Banner">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Account Log"
android:layout_gravity="center"
android:inputType="none"
android:textStyle="bold"/>
</FrameLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Log"
android:layout_toRightOf="#+id/Menu"
android:layout_below="#+id/Banner"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:choiceMode="none"
android:clickable="false"
android:contextClickable="true"
android:fadeScrollbars="true" />
</RelativeLayout>
Assuming that I have a function called getDatafromFile() which returns an ArrayList of data, how do I put those data into my listView?
I've heard of using ArrayAdapter but the examples I've seen puts ListView to the entire layout.
The best way to put data in your ListView is by making an ArrayAdapter Class. I always recommend you to try using a custom adapter class so that you can change it as per your requirement. You can create a class that extends ArrayAdapter. Then pass the arraylist that you want inside your list view to that adapter constructor.
For Example, below is a custom adapter class
public class CustomAdapter extends ArrayAdapter<DataInfo> {
ArrayList<DataInfo> itemList =new ArrayList<>();
Context context;
LayoutInflater inflater;
public CustomAdapte(Context context, ArrayList<VegInfo> list) {
super(context, R.layout.list_item, list);
this.context = context;
itemList = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting an item from the list
DataInfo item = itemList.get(position);
if(convertView==null)
convertView = inflater.inflate(R.layout.list_item,parent,false);
//displaying some data from your data info in a textview
TextView textView = (TextView) convertView.findViewById(R.id.tv);
textView.setText(item.subitem);
return convertView;
}
}
Inside your Activity, You can set the data to that adapter.
CustomAdapter yourAdapter = new CustomAdapte(activity,yourArrayList);
yourListView.setAdapter(yourAdapter);
Now, your list view have the data inside the array list. Whenever there is a change in the array list, it can be reflected in the list view just by calling
yourAdapter.notifydatasetchanged();
Here list_item is a custom XML file that you should create for a single list item view.
Hope this helps you. If not please tell me and let me make it more clear. happy coding.
Full code of create list view
public class MainActivity extends AppCompatActivity {
ArrayList<String>arrayList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //here is the layout where your views exists
for (int i=0;i<=20;i++){
arrayList.add("List Items"+i); //assume we passed the data in arraylist
}
ListView listView=(ListView)findViewById(R.id.log); //your listview
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,arrayList);//the second argument is a layout file that have a textview
listView.setAdapter(arrayAdapter);
}
}
I am aware that other people have asked this question, but I have looked at other solutions and still can't get it to work.
Adapter code:
private class CustomTextAndImageAdapter extends ArrayAdapter<String> {
private Context context;
private Activity activity;
private ArrayList<String> timeArrayList;
private ArrayList<Bitmap> weatherIconArrayList;
private ArrayList<String> descriptionArrayList;
private ArrayList<String> tempArrayList;
private ArrayList<String> popArrayList;
private ArrayList<String> windSpeedArrayList;
public final void setTimeArrayList(ArrayList<String> timeArrayList)
{
this.timeArrayList = timeArrayList;
}
public final void setDescriptionArrayList(ArrayList<String> descriptionArrayList)
{
this.descriptionArrayList = descriptionArrayList;
}
public final void setTempArrayList(ArrayList<String> tempArrayList)
{
this.tempArrayList = tempArrayList;
}
public final void setPopArrayList(ArrayList<String> popArrayList)
{
this.popArrayList = popArrayList;
}
public final void setWindSpeedArrayList(ArrayList<String> windSpeedArrayList)
{
this.windSpeedArrayList = windSpeedArrayList;
}
public final void setWeatherIconArrayList(ArrayList<Bitmap> weatherIconArrayList)
{
this.weatherIconArrayList = weatherIconArrayList;
}
public CustomTextAndImageAdapter(Context context, Activity activity, int resource)
{
super(context, resource);
this.context = context;
this.activity = activity;
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
Log.d(Constants.LOG_TAG, "getView() method called");
LayoutInflater inflater = activity.getLayoutInflater();
View rowView= inflater.inflate(R.layout.itemlistrow, null, false);
TextView timeTextView = (TextView)rowView.findViewById(R.id.time);
timeTextView.setText(timeArrayList.get(position));
Log.d(Constants.LOG_TAG, "Time text view text = " + timeArrayList.get(position));
ImageView iconImageView = (ImageView) rowView.findViewById(R.id.weatherIcon);
iconImageView.setImageBitmap(weatherIconArrayList.get(position));
TextView descriptionTextView = (TextView)rowView.findViewById(R.id.description);
descriptionTextView.setText(descriptionArrayList.get(position));
TextView tempTextView = (TextView)rowView.findViewById(R.id.temp);
tempTextView.setText(tempArrayList.get(position));
TextView popTextView = (TextView)rowView.findViewById(R.id.pop);
popTextView.setText(popArrayList.get(position));
TextView windSpeedTextView = (TextView)rowView.findViewById(R.id.windSpeed);
windSpeedTextView.setText(windSpeedArrayList.get(position));
return rowView;
}
}
List item layout (itemlistrow.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"
android:weightSum="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/weatherIcon"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sunny"
android:id="#+id/description"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="11 C"
android:id="#+id/temp"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "Rain:"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "Wind:"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id = "#+id/pop"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text = "#+id/windSpeed"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In some of the other solutions, it mentions overriding getCount(). Is this what I am doing wrong? If so, how would I know what to put in for getCount(), as there are multiple different ArrayLists used. Is it a case of picking one of them, as they are all the same length, e.g. timeArrayList.size()?
Using multiple ArrayList objects like that kind of defeats the purpose of using an ArrayAdapter, whose idea is to have a single source of items. Not to mention that the code right now doesn't look nice at all.
I'd suggest to first create a Weather object that will hold your data:
public class Weather {
private String time;
private Bitmap weatherIcon;
private String description;
private String temp;
private String pop;
private String windSpeed;
// build object here, provide getters, etc....
.....
}
Than your adapter can be transformed to something simpler like this:
private class CustomTextAndImageAdapter extends ArrayAdapter<Weather>
{
private LayoutInflater inflater;
public CustomTextAndImageAdapter(Context context, Activity activity, int resource, List<Weather> items)
{
super(context, resource, items);
this.inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View view, ViewGroup parent)
{
View rowView= inflater.inflate(R.layout.itemlistrow, null, false);
TextView timeTextView = (TextView)rowView.findViewById(R.id.time);
timeTextView.setText(getItem(position).getTime());
ImageView iconImageView = (ImageView) rowView.findViewById(R.id.weatherIcon);
iconImageView.setImageBitmap(getItem(position).getWeatherIcon());
........
return rowView;
}
}
Main difference is that it's now an ArrayAdapter<Weather> and that you're passing the arguments directly in the constructor of the adapter. Users of the adapter now have to call just 1 constructor, instead of all the final methods that had to be called before.
The other major difference is that you're passing the items list to the super class. Now your adapter knows it's size (internally getCount() will be == items.size()) so getView() will be called appropriately.
As a final thought - the adapter is still not using the ViewHolder pattern, which you should totally implement! There's been numerous posts for it, so just search a bit and you'll find it.
This is not a good way to populate a ListView using an adapter which populates the data from multiple ArrayList. Generally we use a single source of dataset to be passed to an adapter in case of showing a list in Android.
So in your case, when you'll call the notifyDatasetChanged it shouldn't take effect in the list properly as far as I can guess.
notifyDatasetChanged basically calls the getCount function of the adapter and checks if the size of the ArrayList associated with the adapter is changed or not. If the size of the ArrayList is changed, it refreshes the ListView and the getView function gets called.
In your case, I don't see any getCount function though. getCount usually returns the size of the ArrayList associated with the adapter.
So I would suggest, using a single ArrayList to be passed to the adapter. You can merge multiple ArrayList and can use one joined HashMap in your case too. Its your decision, exactly how you can pass a single list of your dataset to the adapter to populate them into a ListView.
I have an custom array adaptor which is handling a list view.
Each row has two checkboxes. There are five rows in total.
I want to be able to count the number of checkboxes ticked and then display this number in Stand1
So basically the project Layout is like this
Inside stand1 there is a list view and a text view.
The stand1.java calls an array adapter Called CustomArrayAdaptor.
I want to be able to count the number of checkboxes clicked and send that data back to the stand1
I am quite new to android development so if somebody can be able to push me in the right direction, it would be great.
Here is my code
Stand1.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">
<ListView
android:layout_width="fill_parent"
android:layout_height="446dp"
android:id="#+id/Stand1list"
android:scrollIndicators="right"
android:smoothScrollbar="true">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Score To Databse"
android:id="#+id/sendtodb"
android:textSize="12dp"
android:clickable="true"
android:layout_below="#+id/Stand1list"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="8/10"
android:id="#+id/Score"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_alignBottom="#+id/sendtodb"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="10dp" />
Row_Layout1.xml
<?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="match_parent"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textelement"
xmlns:android="http://schemas.android.com/apk/res/android"
android:textSize="30dp"
android:textStyle="bold"
android:longClickable="false" />
<CheckBox
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/Checkbox1"
android:button="#drawable/checkboxcustom"
android:layout_marginLeft="50dp" />
<CheckBox
android:button="#drawable/checkboxcustom"
android:id="#+id/Checkbox2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="50dp" />
</LinearLayout>
Stand1.java
public class Stand1 extends Fragment {
ListView mList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.stand1,container,false);
mList = (ListView) root.findViewById(R.id.Stand1list);
return root;
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
populateListView();
}
private void populateListView() {
String[] pair = {"Pair 1","Pair 2","Pair 3","Pair 4","Pair 5"};
//build adapter
ArrayAdapter<String> adapter = new CustomArrayAdaptor(getActivity(),pair);
mList.setAdapter(adapter);
}
}
CustomArrayAdaptor.java
public class CustomArrayAdaptor extends ArrayAdapter<String>{
public CustomArrayAdaptor(Context context, String [] Pairs) {
super(context, R.layout.row_layout1, Pairs);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View CustomView = inflater.inflate(R.layout.row_layout1, parent, false);
String stringelement = getItem(position);
TextView Text= (TextView)CustomView.findViewById(R.id.textelement);
Text.setText(stringelement);
return CustomView;
}
}
Thanks Folks
I added a few things to your CustomArrayAdaptor and tested it, see below:
public class CustomArrayAdapter extends ArrayAdapter<String> {
int checkAccumulator;
public CustomArrayAdapter(Context context, String [] Pairs) {
super(context, R.layout.row_layout1, Pairs);
checkAccumulator = 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View customView = inflater.inflate(R.layout.row_layout1, parent, false);
String stringelement = getItem(position);
TextView Text = (TextView) customView.findViewById(R.id.textelement);
CheckBox checkBox1 = (CheckBox) customView.findViewById(R.id.Checkbox1);
CheckBox checkBox2 = (CheckBox) customView.findViewById(R.id.Checkbox2);
CompoundButton.OnCheckedChangeListener checkListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
countCheck(isChecked);
Log.i("MAIN", checkAccumulator + "");
}
};
checkBox1.setOnCheckedChangeListener(checkListener);
checkBox2.setOnCheckedChangeListener(checkListener);
Text.setText(stringelement);
return customView;
}
private void countCheck(boolean isChecked) {
checkAccumulator += isChecked ? 1 : -1 ;
}
}
Added int checkAccumulator to keep track of how many items have been clicked.
Added two CheckBox Views for the purpose of tracking checks.
Added CompoundButton.OnCheckedChangeListener that calls a new countCheck method everytime any checkBox is checked / unchecked. We pass the isChecked boolean to track whether we need to add or subtract from our checkAccumulator.
Added countCheck function that adds or subtracts 1 dependent on the boolean. Sorry for the obfuscated code, for all those who aren't used to the ? conditional it is basically saying if true add 1, else add -1.
Not sure what you wanted to do with the check count, so I added a Log.i("MAIN", checkAccumulator + ""); just so you can watch the Android Monitor to ensure that it is actually working.
Should work for you.
First of all, you should recycle your views in the adapter:
LayoutInflater inflater = LayoutInflater.from(getContext());
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_layout1, parent, false);
}
After that, I think you should save the state of each checkbox in your data source or just keep a list, the same size of your pair array, and save it there using the position you get from getView.
I am working on an Android application in which I have one container called as Section and there can be Note objects inside it. The use-case is that a user can put multiple notes in a section and organize them. Currently I am to display the section names retrieved from the server with a background image.
Now my problem is how can I display the multiple notes received from the server inside the section.
I understand that this can be achieved by FrameLayout, but a dynamic Note count is what my problem is.
Please note that the count of notes can vary, depending upon user.
Here is the original screenshot of how sections look currently :
Now when you would add notes, it ideally should look like this :
Each of those blocks inside the section contains Note objects. To display its contents, I want to show a note block kind of image and just few words
of the note contents.
Currently I have code to retrieve the Notes from the server, sections can be displayed, but I really have no idea how to proceed because notes can be dynamic. Here is my code so far.
public class GroupSectionActivity extends Activity {
private SectionServiceImpl sectionService = new SectionServiceImpl();
private NoteServiceImpl noteService = new NoteServiceImpl();
private static volatile List<RestSection> restSectionList = new ArrayList<>();
private static volatile List<RestNote> restNoteList = new ArrayList<>();
private static volatile Long groupAccountId;
private static volatile Integer canvasid;
ListView listView;
SectionLazyAdapter sectionLazyAdapter;
static final String msectionname = "msectionname";
static final String msectionid = "msectionid";
Button addSectionButton;
EditText sectionName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sectionlayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
groupAccountId = extras.getLong("groupid");
canvasid = extras.getInt("canvasid");
}
restSectionList = this.sectionService.getSectionByCanvas(canvasid);
ArrayList<HashMap<String, String>> restSectionArrayList = new ArrayList<HashMap<String, String>>();
for (RestSection restSection : restSectionList) {
HashMap<String, String> sectionDisplay = new HashMap<>();
sectionDisplay.put("msectionid", String.valueOf(restSection.getMsectionid()));
sectionDisplay.put("msectionname", restSection.getMsectionname());
restSectionArrayList.add(sectionDisplay);
}
listView = (ListView) findViewById(R.id.seclist);
sectionLazyAdapter = new SectionLazyAdapter(this, restSectionArrayList);
listView.setAdapter(sectionLazyAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int sectionId = restSectionList.get(position).getMsectionid();
Log.d("Sectionid is ", String.valueOf(sectionId));
/*Intent intent = new Intent(GroupSectionActivity.this, GroupSectionActivity.class);
intent.putExtra("groupid", groupAccountId);
intent.putExtra("sectionid", sectionId);
startActivity(intent);
finish();*/
}
});
BaseAdapter to manage the guys :
public class SectionLazyAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public SectionLazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_group_section, null);
TextView sectionName = (TextView)vi.findViewById(R.id.sectionname); // title
// ImageView sectionImage=(ImageView)vi.findViewById(R.id.sectionimage); // thumb image
HashMap<String, String> sectionList = new HashMap<String, String>();
sectionList = data.get(position);
// Setting all values in listview
sectionName.setText(sectionList.get(GroupSectionActivity.msectionname));
return vi;
}
}
activity_group_section.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<ImageView
android:id="#+id/sectionimage"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:scaleType="fitXY"
android:src="#drawable/sectionbackground"
/>
</FrameLayout>
<TextView
android:id="#+id/sectionname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textView"
android:visibility="visible"
android:gravity="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
sectionlayout.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"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#+id/seclist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/sectionAddButton">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sectionAddButton"
android:layout_alignParentTop="true"
android:background="#drawable/sectionbackground"
android:text="Add Section" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sectionNameTextField"
android:layout_alignBottom="#+id/sectionAddButton"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toEndOf="#+id/sectionAddButton"
android:hint="Section Name"
android:gravity="center"
android:layout_toRightOf="#+id/sectionAddButton" />
</RelativeLayout>
I hope the question is clear, if there is anything missing, kindly let me know.
If you want to display the notes in a dynamic way, you should implement a GridView inside each container, if you set the right margin to each note inside the Grid, the component will dimension itself to fit your section.
The GridView adapter is really simple, works just like the ListView adapter, you will just need to define the number of columns, you can do this in the XML, or programmatically in your Java code.
<GridView
android:id="#+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"/>
First let me point out that Thomaz is right and you should use a GridView.
It's the right way to go both for your needs and ease of use, but more importantly for it's ability to recycle it's views.
If you won't use any form of view recycling you might get out of memory exception.
But now you face another problem: you want it to be shown in sections.
Why is that a problem? Because:
A) Both the ListView and the GridView do recycling with their child views, and now that each child view of the ListView is a single GridView, which holds inside of it more Views, it's a pretty complex thing to manage. No impossible, but pretty complex.
B) Because of the fact that both the ListView and the GridView are scrollable (and because of that fact are recyclable) there is an issue of scrolling inside scrolling that needs to be resolved.
Luckily I cam across an answer: SuperSLiM (Formally StickyGridHeaders).
This should provide you with an easy solution which suites your needs.
Good luck.
Problem
I'm trying to create a ListView with selectable items. I want to be able to click on an item in the ListView and have the item change color in the list, and then go on and do something else with the data from the row.
I'm using a SimpleAdapter.
How do I make it so that when I tap on a row, it turns a different color, and then when I tap on a different row, the new row is selected and changed to a new color, and the old row changes back to normal?
Code
Here is my code so far. The DBTools class is has all of the data that I want to be displayed in my ListView organized and taken care of. The getAllReceivers() method returns an ArrayList of HashMap<String, String>s that have all of my data.
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] {"receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath});
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>
Solution
The solution to this problem is very simple. We need to add an OnItemClickListener to our ListView to listen for clicks and respond accordingly.
So, in the onCreate() method, once you've made sure that you set of data isn't empty, you're going to want to Override the onItemClick() method to listen for the click and change the color. You're also going to want to keep track of which item you selected for the later steps, so add public int selectionId = -1; at the top of your class. Furthermore, you'll need to let the ListAdapter know that you changed something by calling ((SimpleAdapter) getListAdapter()).notifyDataSetChanged().
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = getNewAdapter();
setListAdapter(adapter);
}
Great! Now we have a working system that will change the color of the row that you tap. But we're not done yet. We need to make sure that the previous selection changes back to the normal color.
For this, we are going to use override the SimpleAdapter's getView() method, which is called everytime the ListView goes to draw the items being displayed in it.
It only actually displays the items it needs to - the ones that you can see. It does not render the ones above or below your screen. So if you have 200 items in a ListView, only 5 or 6, depending on the size of your screen and the size of the items, are being rendered at a time.
To override the getView() method, go up to where you initialize the adapter and change the code to this:
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
Every time one of the rows is drawn, since the getView() will get called, the ListView will check if the current view has the id of row you selected. If it doesn't, it'll change the background color to white. If it does, it'll change the background color to red.
And voila! That's it! Now you are setting the background color to red when you click on an item in the ListView.
Final Code
MainActivity.java:
public class MainActivity extends ListActivity {
DBTools dbTools = new DBTools(this);
ArrayList<HashMap<String, String>> receiverList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.activity_main);
receiverList = dbTools.getAllReceivers();
dbTools.close();
ListView listView = getListView();
if(receiverList.size() != 0) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
view.setBackgroundColor(Color.RED);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
selectionId = Integer.valueOf(receiverIdTextView.getText().toString());
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
});
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,receiverList, R.layout.receiver_entry, new String[] { "receiverId","receiverName", "fullPath"}, new int[] {R.id.receiverId, R.id.receiverName, R.id.fullPath}) {
#Override
public View getView (int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView receiverIdTextView = (TextView) view.findViewById(R.id.receiverId);
if(receiverIdTextView.getText().toString().equals(String.valueOf(selectionId))) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
return view;
}
};
setListAdapter(adapter);
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TextView
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="My List" />
</TableRow>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:id="#android:id/list" />
</TableLayout>
receiver_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tableRow" >
<TextView
android:id="#+id/receiverId"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/receiverName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Robotronics" />
<TextView
android:id="#+id/fullPath"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123.45.678.910:8088/robtrox/find" />
</TableRow>