Add icons to Listview using Arraylist - java

I have successfully created a listview that contains all the options (text). However I would like to add unique icons next to each of the options. How can I go about doing this, with my excising code?
Here is what I am trying to achieve:
Here is my code:
AccountSettingsActivity.java
//All Options in Account Settings
private void setupSettingsList(){
ListView listView = findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString((R.string.editProfile)));
options.add(getString(R.string.notifications));
options.add(getString(R.string.privacy_settings));
options.add(getString(R.string.security));
options.add(getString(R.string.ads));
options.add(getString(R.string.help));
options.add(getString(R.string.about));
options.add(getString(R.string.logout));
ArrayAdapter adapter = new ArrayAdapter(mContext, R.layout.listview_row_adjustment, options);
listView.setAdapter((adapter));
}
listview_row_adjustmnet.xml (This simply changes the text color and size of the options in the listview)
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listViewAdjustment"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textSize="17sp"
android:gravity="fill"
android:textColor="#color/white"/>

Create Array in /res folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="images">
<item>#drawable/img1</item>
<item>#drawable/img2</item>
<item>#drawable/img3</item>
</array>
</resources>
update Account Setting:
//All Options in Account Settings
private void setupSettingsList(){
ListView listView = findViewById(R.id.lvAccountSettings);
TypedArray images = getResources().obtainTypedArray(R.array.images);
ArrayList<String> options = new ArrayList<>();
options.add(getString((R.string.editProfile)));
options.add(getString(R.string.notifications));
options.add(getString(R.string.privacy_settings));
options.add(getString(R.string.security));
options.add(getString(R.string.ads));
options.add(getString(R.string.help));
options.add(getString(R.string.about));
options.add(getString(R.string.logout));
// add images to adapter
ArrayAdapter adapter = new ArrayAdapter(mContext, R.layout.listview_row_adjustment, options, images);
listView.setAdapter((adapter));
}
Add Image View in listview_row_adjustmnet.xml
in Adapter set the image:
imageView.setImageResource(images.getResourceId(i, -1));

Use a data model with title and icon like below
class Data {
public int imageId;
public String txt;
Data(Drawable imageId, String text) {
this.imageId = imageId;
this.txt = text;
}
}
Data menuItemSearch = new Data(ContextCompat.getDrawable(this, R.drawable.ic_search_orange), resources.getString(R.string.title))
and when set drawable in image use this one
yourImage.setImageDrawable(data.imageId)

Firstly, You have to add in your listview_row_adjustmnet.xml.
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal|top"/>
<TextView
android:id="#+id/listViewAdjustment"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textSize="17sp"
android:gravity="fill"
android:textColor="#color/white"/>
And for Code AccountSettingActivity class:
private void setupSettingsList(){
ListView listView = findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString((R.string.editProfile)));
options.add(getString(R.string.notifications));
options.add(getString(R.string.privacy_settings));
options.add(getString(R.string.security));
options.add(getString(R.string.ads));
options.add(getString(R.string.help));
options.add(getString(R.string.about));
options.add(getString(R.string.logout));
ArrayList<ImageView> images = new ArrayList<>();
//Please add Customized addapter
}
for the customized adapter, you find help in this Link https://www.youtube.com/watch?v=_YF6ocdPaBg.
To set an ImageView in code Please see this answer Using variable to change image in Java.

Related

Displaying ListView on Android

How do I create a working ListView in Android?
I am not looking for you to just fix my code, but am looking for a simple working example of a ListView in Android so I can understand the process of creating one and working with it. But I have included my code so you can see where I am coming from and what I have been trying.
I have done the following and had no success:
--
Made a xml layout with only a TextView item in it:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/dir_text_view"
/>
Created the following class as per the instructions at the following tutorial:
http://www.vogella.com/tutorials/AndroidListView/article.html
public class DataTempleArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public DataTempleArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
And in the main activity I have a snippet of code where I attempt to add a list of strings to the ArrayList associated with the DataTempleArrayAdapter here:
int i;
for (i=0;i<dirContents.length;i++) {
dirList.add(dirContents[i]);
//Toast.makeText(this, dirList.get(i), Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
dirList is successfully populated, while the adapter doesn't update the ListView at all.
--
Before you ask for it, here I am including the rest of the relevant code:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="org.hacktivity.datatemple.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="#string/directory"
android:ems="10"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/dirEditText" />
<Button
android:text="→"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/dirButton"
android:onClick="populateDirList" />
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="#+id/dirListView" />
</LinearLayout>
</RelativeLayout>
And alas the MainActivity class:
public class MainActivity extends AppCompatActivity {
ListView dirListView;
EditText et;
DataTempleArrayAdapter adapter;
ArrayList<String> dirList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dirListView = (ListView) findViewById(R.id.dirListView);
et = (EditText) findViewById(R.id.dirEditText);
dirList = new ArrayList<String>();
dirListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
populateDirList(view);
}
});
ArrayList<String> dirList = new ArrayList<String>();
adapter = new DataTempleArrayAdapter(this,
R.id.dir_text_view, dirList);
dirListView.setAdapter(adapter);
}
public void populateDirList (View view) {
File f;
// NO INPUT.
if (et.getText().toString().equals("")) {
Toast.makeText(this, "empty string", Toast.LENGTH_SHORT).show();
return;
}
f = new File(et.getText().toString());
if (f == null) { return; }
String dirContents[] = f.list();
if (dirContents == null) { return; }
dirList = new ArrayList<String>(Arrays.asList(f.list()));
adapter.clear();
int i;
for (i=0;i<dirContents.length;i++) {
dirList.add(dirContents[i]);
//Toast.makeText(this, dirList.get(i), Toast.LENGTH_SHORT).show();
}
adapter.notifyDataSetChanged();
}
}
One of the best resources for understanding ListView is indeed the
one you mentioned from Vogella
Another cool resource to understand how the the
notifyDataSetChanged() method works in ListView this post from StackOverflow
For a short, simple explanation of how to use CustomLayouts in
ListView (without the ViewHolder pattern) check another of the best
references available: Mkyong
Discussing the benefits of the ViewHolder pattern in ListView:
check this StackOverflow post
Concise example and explanation of the ViewHolder pattern in
ListView: check this example from JavaCodeGeeks
And to fix your code I think the answer given before is only part of the problem:
You must indeed comment the line
//ArrayList<String> dirList = new ArrayList<String>();
because, like #F43nd1r mentioned this would also be a different instance of a list passed into the adapter
but there is more, when you do this:
dirList = new ArrayList<String>(Arrays.asList(f.list()));
you are instantiating a new, different, list, the old reference held by the adapter will NOT be changed... it will still hold the OLD object list
you should perhaps substitute it for something like:
dirList.clear();
dirList.addAll(Arrays.asList(f.list()));
Hope this helps!
Excerpt from your code:
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
dirList = new ArrayList<String>();
//...
ArrayList<String> dirList = new ArrayList<String>();
adapter = new DataTempleArrayAdapter(this,
R.id.dir_text_view, dirList);
//...
}
I bet you already see what the problem is, but in case you don't: You have a field and a local variable with the same name. You pass the local variable to the adapter. It is only naturally that the adapter does not react to changes on the field, as it has no knowledge of its existence.
I think what you have done wrong is to supply a UI Component to the Array Adapter with:
adapter = new DataTempleArrayAdapter(this, R.id.dir_text_view, dirList);
The second item should not be an ID, but a layout file. Android have already implemented a List item layout with a textview that you can use: android.R.layout.simple_list_item_1.
so replace your row with
adapter = new DataTempleArrayAdapter(this, android.R.layout.simple_list_item_1, dirList);
and you are one step closer.
(This way you don't need your "xml layout with only a TextView item in it")

ImageView inside ListView is ignoring all layout dimensions and filling the whole screen

I'm trying to create a set of 4 dynamically updating listviews of icons.
To do this, I've put my 4 listviews inside a gridview, and I'm using a custom layout for each listview item with a single imageview inside it. I'm handling changing the icon inside a custom adapter. I'm using the Picasso library to handle the icons, and all my icons are stored locally in drawable as .png files.
I'm not getting any errors, but when I run the app, all I get is a single icon that takes up the whole screen. I have a small imageview and a textview above the gridview that contains the lists of icons, but the one icon pushes even that out of the way.
This is my layout preview, and a screenshot of the app running in an emulator. (the result is the same if I run on my phone).
preview,
running
(apologies for not embedding, I'm new to SO, and don't have 10 rep yet haha)
I've tried resizing the image at runtime inside my custom adapter. I've tried setting the maximum width of the listview - both at runtime (since I want to adapt to different screen dimensions), and in the xml files. I've tried resizing the source .png files outside of android studio. Nothing's worked.
My activity xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.sta.tomov0.MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tomoFace"
android:src="#drawable/office38"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="100dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:layout_below="#+id/tomoFace"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="false"
android:layout_marginBottom="50dp" />
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:rowCount="1"
android:id="#+id/gridLayout"
android:layout_below="#+id/textView"
android:columnCount="5">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewA"
android:layout_row="0"
android:layout_column="0" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewB"
android:layout_row="0"
android:layout_column="1" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewC"
android:layout_row="0"
android:layout_column="2" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewD"
android:layout_column="3"
android:layout_row="0" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:layout_column="4"
android:layout_row="0"
android:onClick="addTask"
android:src="#android:drawable/stat_notify_more" />
</GridLayout>
</RelativeLayout>
My listview layout:
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listImageView"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false" />
</RelativeLayout>
and my activity.java file:
public class MainActivity extends AppCompatActivity {
ImageView tomoface;
ListView listViewA;
ArrayList arrayListA = new ArrayList<Integer>();
Boolean aExists = false;
ListView listViewB;
ArrayList arrayListB = new ArrayList<Integer>();
Boolean bExists = false;
ListView listViewC;
ArrayList arrayListC = new ArrayList<Integer>();
Boolean cExists = false;
ListView listViewD;
ArrayList arrayListD = new ArrayList<Integer>();
Boolean dExists = false;
Button addButton;
TextView tomoText;
File tomoFiles;
File taskFiles;
String currentCommunity = "Dep";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Paper.init(getApplicationContext());
tomoface = (ImageView) findViewById(R.id.tomoFace);
tomoface.setImageResource(R.drawable.favourite15);
tomoText = (TextView) findViewById(R.id.textView);
listViewA = (ListView) findViewById(R.id.listViewA);
listViewB = (ListView) findViewById(R.id.listViewB);
listViewC = (ListView) findViewById(R.id.listViewC);
listViewD = (ListView) findViewById(R.id.listViewD);
tomoFiles = getDir("TomoFiles", MODE_PRIVATE);
taskFiles = new File(tomoFiles, "taskFiles");
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width =(size.x)/5;
ViewGroup.LayoutParams params = listViewA.getLayoutParams();
params.height = width;
params.width = width;
listViewA.setLayoutParams(params);
listViewB.setLayoutParams(params);
listViewC.setLayoutParams(params);
listViewD.setLayoutParams(params);
/*
If there is no data saved, the following code creates a list of (empty) lists to hold TaskClass objects
The 4 sub lists each represent one category.
If there is data saved, the following code retrieves that data, and creates 4 new ArrayLists,
each containing the iconIds of the TaskClass objects in the corresponding position of the corresponding TaskClass arraylist.
These ArrayLists of ids are then used to populate the 4 listviews.
*/
ArrayList<ArrayList<TaskClass>> listList = Paper.book(currentCommunity).read("listList", new ArrayList<ArrayList<TaskClass>>());
if (listList.size() == 0){
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
listList.add(new ArrayList<TaskClass>());
} else {
for(TaskClass t:listList.get(0)){
arrayListA.add(t.getIcon());
}
for(TaskClass t:listList.get(1)){
arrayListB.add(t.getIcon());
}
for(TaskClass t:listList.get(2)){
arrayListC.add(t.getIcon());
}
for(TaskClass t:listList.get(3)){
arrayListD.add(t.getIcon());
}
}
Integer[] intArrayA = new Integer[arrayListA.size()];
for (int i = 0; i < arrayListA.size(); i++){
intArrayA[i] =(Integer) arrayListA.get(i);
}
ArrayAdapter adapterA = new CustomArrayAdapter(getApplicationContext(),intArrayA);
listViewA.setAdapter(adapterA);
Integer[] intArrayB = new Integer[arrayListB.size()];
for (int i = 0; i < arrayListB.size(); i++){
intArrayB[i] =(Integer) arrayListB.get(i);
}
ArrayAdapter adapterB = new CustomArrayAdapter(getApplicationContext(),intArrayB);
listViewB.setAdapter(adapterB);
Integer[] intArrayC = new Integer[arrayListC.size()];
for (int i = 0; i < arrayListC.size(); i++){
intArrayC[i] =(Integer) arrayListC.get(i);
}
ArrayAdapter adapterC = new CustomArrayAdapter(getApplicationContext(),intArrayC);
listViewC.setAdapter(adapterC);
Integer[] intArrayD = new Integer[arrayListD.size()];
for (int i = 0; i < arrayListD.size(); i++){
intArrayD[i] =(Integer) arrayListD.get(i);
}
ArrayAdapter adapterD = new CustomArrayAdapter(getApplicationContext(),intArrayD);
listViewD.setAdapter(adapterD);
}
//TODO: create a custom adapter that will display icons correctly
public class CustomArrayAdapter extends ArrayAdapter{
private final Context context;
private final Integer[] values;
public CustomArrayAdapter(Context context, Integer[] values) {
super(context, -1, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View iconView = inflater.inflate(R.layout.iconlayout, parent, false);
ImageView imageView = (ImageView) iconView.findViewById(R.id.listImageView);
int s =(int) values[position];
imageView.setImageResource(s);
//get the device width, to calculate icon width, and then set icon width accordingly
//TODO: setting icon width not working
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width =(size.x)/5;
Uri uri = Uri.parse("android.resource://com.example.sta.tomov0/drawable/"+s);
Picasso.with(context).load(uri).resize(width,width).fit().centerCrop().into(imageView);
return iconView;
}
}
}
A note: I have a custom data management class that returns arraylists. That's tested separately and working fine. The arraylists that are being fed to the adapter are int arraylists of the drawable references.
Help! What am I doing wrong? I've been searching through SO all day and trying different things. The solutions posted in these questions haven't helped T-T:
How to set ImageView width in android ListView?
ImageView in ListView that expands maximum width
(that was a bit difficult to implement, and just created other problems - it seems like overkill to create a custom view class just for displaying an icon?)
Give fixed height to your Imageview in My listview layout:
Say Something like
<?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="wrap_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="120dp"
android:id="#+id/listImageView"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false" />
</RelativeLayout>
I'm assuming #drawable/office38 is the image shown in your screenshot (taking up the whole screen)?
Try setting the dimensions of this image to something small, eg:
android:layout_width="50dp"
android:layout_height="50dp"
I know this may not be what you are actually looking to do, but at least it will show you if the problem is with that first ImageView or not and will free up space below it for the TextView and the GridLayout. It could be that the drawable is massive, and as you aren't specifying a set width/height or any scale options, it takes up all the space it can.
Also, have a look at http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType which describes the different scaling options you have with an ImageView.
GOT IT.
sorry guys. It was a really dumb problem after all.
My listview adapter is working fine it turns out. The problem was in the imageview that was outside of the lists (tomoface) - for some reason, I decided to set it to a different drawable on runtime, and hadn't scaled that at all haha.

Set background for items in a spinner using a drawable resource - java android studio

I've created a spinner using the code below. Now I want to use a drawable resource called circle.xml, to set the background for each item in the spinner so that each number appears inside a circle.
Spinner equationSpinner = new Spinner(this);
ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("");
spinnerArray.add("1");
spinnerArray.add("2");
spinnerArray.add("3");
spinnerArray.add("4");
spinnerArray.add("5");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
equationSpinner.setAdapter(spinnerArrayAdapter);
I can use the circle as a background in a TextView so I tried creating the spinnerArray as an array of TextViews but that appeared to be incompatible with the simple_spinner_dropdown_item.
Anybody have an idea how I can do this? I just want each number to appear inside a circle in the spinner. I will also need to be able to access the number selected in the spinner.
Thanks
P.S. Is there any way in Android to create a 'slot machine' style spinner like you have in iOS? I prefer the look of those.
EDIT:
I've now found that I can use my circle resource by creating a custom layout (called spinner_item.xml) like this:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="28dip"
android:layout_height="28dip"
android:gravity="center"
android:textSize="20sp"
android:background="#drawable/circle"
android:textColor="#ff0000" />
I then set the adapter for my spinner programmatically like this:
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.equations, R.layout.spinner_item);
adapter.setDropDownViewResource(R.layout.spinner_item);
equationSpinner.setAdapter(adapter);
However, this method requires that I have a predefined string array set up in my strings.xml file (R.array.equations). I need to be able to specify the array of strings to be used programmatically depending on the state of the app. Can I modify the array once its set up?
EDIT 2:
Additionally I've found I can set the background of the dropdown items and use my own programmatical array like this:
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
equationSpinner.setAdapter(spinnerArrayAdapter);
The only problem then is being able to apply the resource to the background of the spinner itself (not the drop down items). There does not appear to be an equivalent to setDropDownViewResource for the main spinner item.
lets say textview_background.xml is the background you want to give to the textView to Spinner
make a file in drawable and name it this textview_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/holo_blue_dark" />
<corners android:radius="7dp" />
<stroke
android:width="3dp"
android:color="#android:color/tertiary_text_light" />
</shape>
make a Spinner in your activity
<Spinner
android:id="#+id/SpinnerOneActivity_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
make a layout with name list_text_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:padding="4dp"
android:text="some"
android:background="#drawable/textview_background"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#android:color/black" />
make a class which will fill data from a list to your spinner, in this code your Adapter class is taking list of String but you can have your own custom object list given to it to populate the spinner, watch out how adapter's constructor parameters.
first-Context
Second-layout which will be given to each item in spinner
Third-a textView id from the above layout
Forth-your list of objects which you want to populate
TestAdapter.java
public class TestAdapter extends ArrayAdapter {
private ArrayList<String> strings;
private Context context;
private LayoutInflater layoutInflater;
public TestAdapter(Context context, int resource,int id, ArrayList<String> strings) {
super(context, resource, id, strings);
this.context = context;
this.strings = strings;
this.layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = layoutInflater.inflate(R.layout.list_text_view, parent, false);
TextView textView = (TextView) view.findViewById(R.id.text1);
textView.setText("" + strings.get(position));
return view;
}
}
in your activity you can write this code
ArrayList<String> list = new ArrayList<>();
list.add("one");
list.add("Two");
list.add("Three");
list.add("four");
Spinner spinner = (Spinner) findViewById(R.id.SpinnerOneActivity_spinner);
spinner.setAdapter(new TestAdapter(getApplicationContext(), R.layout.list_text_view, R.id.text1,list));
As you wanted you can increase the list or generate things dynamically to add or remove from the list once your list is attached to adapter which will be provided to Spinner you can call notifyDataSetChanged() on adapter to updated the list
Check this answer about Android Wheel: https://stackoverflow.com/a/9503372/3677394
There's a very good 3rd party open source project called Android Wheel
that pretty much does everything involved in creating a slot machine
for you. And if you want to customise it, it's under an Apache
licence, so no issues there.

Android : Displaying multiple smaller images on top of big image and text inside small image

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.

create an Android Scroll List programmatically

Coming from a web dev background, what I'm looking for should be quite simple. I have pulled all the contacts from the android phone.
Their names and numbers are in a HashMap called contacts (number = key) I'm iterating through them and I'm looking to create a list of them for the user to see. The key (the phone number) must be available there but not be seen, and The List must scroll. So something like the <option value="phone">Name</option> would be perfect. I'm stuck. Any ideas?
Use an adapter to inflate the list into ListView.
Like:
public class SimpleListView extends ListActivity {
private String[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
private ArrayList<String> selectedItems = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
// Prepare an ArrayList of todo items
ArrayList<String> listTODO = [INSERT THE VALUES FROM THE CONTACTS HERE];
this.mainListView = getListView();
// Bind the data with the list
lv_arr = listTODO.toArray(new String[0]);
mainListView.setAdapter(new ArrayAdapter<String>(SimpleListView.this,
android.R.layout.simple_list_item_2, lv_arr));
}
}
You also need a layout:
simple.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="450dp" >
<ListView
android:id="#+id/mainListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/size"
android:layout_below="#+id/editText1"
android:gravity="fill_vertical|fill_horizontal"
android:horizontalSpacing="15dp"
android:isScrollContainer="true"
android:numColumns="1"
android:padding="5dp"
android:scrollbars="vertical"
android:smoothScrollbar="true"
android:stretchMode="columnWidth" >
</ListView>
</RelativeLayout>

Categories