android: remove a view from a gallery - android

I'm using a Gallery view in my app. The app is designed so that I can drag and drop a view from that Gallery.
How can I remove the dragged view from the Gallery?

You remove it from the underlying adapter. If you do this correctly, the Gallery will refresh itself. Otherwise, call notifyDataSetChanged() on the adapter to trigger a Gallery update.

If you override ImageAdapter you can modify the contents at will by adding methods to delete or add items to your image list(s) or in the case of the example, completely swap lists on the fly. I am displaying a app banner at startup, and then changing the Gallery to display the mode the app is in as a slider. Whenever you call a method that modifies the dataset in the ImageAdapter, call imageAdapter.notifyDataSetChanged() as CommonsWare says above :
// in onCreate
_gallery = (Gallery) this.findViewById(R.id.gallery_header);
_imageAdapter = new ImageAdapter(getApplicationContext(),screen_width,screen_height);
_imageAdapter.setBannerMode(true);
_gallery.setAdapter(_imageAdapter);
// the main activity, in my case in a message handler.
_imageAdapter.setBannerMode(false);
_imageAdapter.notifyDataSetChanged();
_gallery.setSelection(0,true);
// this is my extended image adapter class
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
public class ImageAdapter extends BaseAdapter
{
private Context _context = null;
private int[] imageIds = { R.drawable.add_banner,R.drawable.subtract_banner,R.drawable.multiply_banner,R.drawable.divide_banner };
private int[] bannerIds = { R.drawable.mathpiggie_banner };
private static boolean bannerEnabled = true;
int _screen_width;
int _screen_height;
public ImageAdapter(Context context, int screen_width, int screen_height) {
this._context = context;
_screen_width = screen_width;
_screen_height = screen_height;
}
public void setBannerMode(boolean val)
{
bannerEnabled = val;
}
#Override
public int getCount()
{
if (bannerEnabled)
return bannerIds.length;
else
return imageIds.length;
}
#Override
public Object getItem(int index)
{
if (bannerEnabled)
return bannerIds[index];
else
return imageIds[index];
}
#Override
public long getItemId(int index)
{
return index;
}
#Override
public View getView(int postion, View view, ViewGroup group)
{
ImageView imageView = new ImageView(_context);
if (bannerEnabled)
imageView.setImageResource(bannerIds[postion]);
else
imageView.setImageResource(imageIds[postion]);
return imageView;
}
}

Related

Android: Using two different Adapters for a Gridview grid

I was wondering if it is possible to apply two different Adapters (ArrayAdapter for a String array, and ImageAdapter for the background of each value in the array) for a certain 4X4 dimension grid… I ask this because my actual (the code below is just a sample) program contains user-inputted values for height and width (https://stackoverflow.com/questions/35382979/android-auto-fitting-row-height-of-gridview-based-on-user-inputted-values) as opposed to hardcoding. Say, if I wanted to assign the brown blocks as a background for the odd numbers, and the gray blocks for the even numbers using grid.setAdapter() for both Adapters... How would I code that using Android Studio?
Here's the following Java code for the grid:
package dpark.sample;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private int height, width;
String[] list;
GridView grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
height = 4;
width = 4;
buildList();
grid = (GridView)findViewById(R.id.gridView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, list);
grid.setAdapter(adapter);
grid.setNumColumns(width);
//***TEMPORARILY COMMENTING THE FOLLOWING OUT SINCE THIS WILL JUST OVERWRITE THE
// ARRAYADAPTER***
//grid.setAdapter(new ImageAdapter(getApplicationContext()));
}
private void buildList() {
int tempIncrementor = 1;
int dimensions = height * width;
list = new String[dimensions];
for (int i = 0; i < dimensions; i++) {
list[i] = String.valueOf(tempIncrementor);
tempIncrementor++;
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.brownblock,
R.drawable.grayblock
};
}
}
... Which outputs in the virtual emulator:
... As for outputting the color block images, I temporarily commented out the ArrayAdapter blocks in my code so I could output the following:
No you can't set two adapters beacuse the method setAdapter overrides the previous one.
But your goal doesn't require it, you should store the values in arraylist and retrieve them in the getView method.

How to extract all the editText's data from a ListView when one single button (save) is pressed

This is the first question I am posting. Here is my question and below given is the debugged code from android studio.
Here, I have tried to extract the data by taking the data from the adapter into the mainActvity, but I failed as the app is crashing on Clicking the save button. Here the data is nothing but and object.
MainActivity :
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ListItem_Elements> testsList;
int n=5;//No. of tests
Button btn_save;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
btn_save= (Button)findViewById(R.id.btn_save);
//CustomAdapter adapter;
Resources res=getResources();//Takes the resource permission required to show ListView
testsList= new ArrayList<ListItem_Elements>();
testsList = SetList();
adapter= new CustomAdapter(this, testsList, res);
listView.setAdapter(adapter);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(testsList!=null)
saveValues();
}
});
}
public ArrayList<ListItem_Elements> SetList() {
/*Enter the Test names*/
ArrayList<ListItem_Elements>tests_Array= new ArrayList<ListItem_Elements>();
for(int i=0;i<5;i++) {
ListItem_Elements e = new ListItem_Elements();
e.setTest("XYZ");
e.setResult(null);
tests_Array.add(e);
}
return tests_Array;
}
ArrayList<ListItem_Elements>ar= new ArrayList<>();
public void saveValues() {
if(adapter.extractedArray!=null) {
ar = adapter.extractedArray;
Toast.makeText(MainActivity.this, ar.size(), Toast.LENGTH_SHORT).show();
}
}
}
--------------------------------------------------------------------------------
CustomAdapter :
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList<ListItem_Elements> extractedArray= new ArrayList<ListItem_Elements>();
private ArrayList<ListItem_Elements> array;
//Declaration of ArrayList which will be used to recieve the ArrayList that has to be putup into the ListView
private LayoutInflater inflater; //To Instantiates a layout XML file into its corresponding View
Resources res;
//protected String bridgeValue;
CustomAdapter(Activity a, ArrayList<ListItem_Elements> b, Resources resLocal) {
activity = a;
array= b;
res = resLocal;
//Initialization of inflater to link the layout of list items
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public CustomAdapter() {
}
#Override
public int getCount() {
return array.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
// keeping references for views we use view holder
public static class ViewHolder {
/*Declaration of elements of layout of list items in the class for future use of putting up
data onto the List View*/
TextView textView;
EditText editText;
}
#Override
//Here views were bound to a position
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
// if a view is null(which is for the first item) then create view
if (convertView == null) {
vi = inflater.inflate(R.layout.layout_items, null);
// Taking XML files that define the layout of items, and converting them into View objects.
holder = new ViewHolder();//Stores the elements of the layout of list items
/*Initializing the elements of the layout of list item*/
holder.textView = (TextView) vi.findViewById(R.id.textView);
holder.editText = (EditText) vi.findViewById(R.id.editText);
vi.setTag(holder);
//Stores the view(layout of list item) into vi
}
//else if it already exists, reuse it(for all the next items). Inflate is costly process.
else {
holder = (ViewHolder) vi.getTag();
//Restores the already exisiting view in the 'vi'
}
/*Setting the arrayList data onto the different elements of the layout of list item*/
try {
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
}
catch (Exception e) {
e.getMessage();
}
return vi;//Returns the view stored in vi i.e contents of layout of list items
}
}
--------------------------------------------------------------------------------
public class ListItem_Elements {
String test;
String result;
ListItem_Elements() {
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
You are missing some necessary code. EditText has a method called addTextChangedListener() which accepts a TextWatcher implementation. This implementation would be responsible for updating the data in the adapter.
final ListItem_Elements item = array.get(position);
holder.textView.setText(item.getTest());
holder.editText.setText(item.getResult());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
item.setResult(s.toString());
}
// omitted empty impls for beforeTextChanged() and afterTextChanged(), you need to add them
});
Now, everytime the user updates the EditText, your adapter value will be updated. Then you just get the array values:
public void saveValues() {
// testLists in the activity and array in the adapter are references
// to the same list. So testLists already has the updated results
}
And take out this whole block of code:
holder.textView.setText(array.get(position).getTest());
if(holder.editText.getText()!=null) {
ListItem_Elements obj = new ListItem_Elements();
obj.setTest(array.get(position).getTest());
obj.setResult(holder.editText.getText().toString());
extractedArray.add(position, obj);
}
It doesn't do the right thing.
you are filling the listView with value from an ArrayList. Why you don't just get values from the your ArrayList ??
public void saveValues() {
if(tests_Array!=null) {
//and here you get values from your list
//by a simple for instruction
Toast.makeText(MainActivity.this, tests_Array.size(), Toast.LENGTH_SHORT).show();
}
}

load a few json elements at a time by scrollview

I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}
In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}

values arent being passed to intent

Stack Trace
Picture of stack trace here
Values aren't being passed to the other intent. Every time I try to start the activity with the intent in it, it crashes.
//This activity will retrieve and display the different rewards that are available.
public class RewardsActivity extends Activity {
#Override
public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
setContentView(R.layout.rewards);
//stores retrieves and stores the current gridview
GridView gridView = (GridView)findViewById(R.id.grid_view);
//Instance of ImageAdapter class that will load the images into the gridview
gridView.setAdapter(new ImageAdapter(this));
//This function is used to set a listener on each item in the grid so that when its clicked it will go to the other view.
gridView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
Intent i = new Intent(getApplicationContext(),RewardsViewActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
This new intent is being passed to, when it's passed here it is stored in a variable then used in a ImageView to load an image.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class RewardsViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_view);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image);
imageView.setImageResource(imageAdapter.finalImages[position]);
}
}
ImageAdapter.java
package org.android.pps;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/*This class will be used handle the loading of the image view that will display all the
images of the rewards. (this will be used along with RewardsActivity and rewards.xml)
*/
public class ImageAdapter extends BaseAdapter {
//variable that will store the current context of the application
private Context c;
private Integer num = 6;
private int[] rewards_num=new int[num];
private Integer[] Images = new Integer[6];
public Integer[] finalImages;
//for loop will set the correct image to the array if its either activated or deactivated
public Integer[] fillImageArray()
{
//Array that will be used to show the reward images
Integer[] Activated ={
R.drawable.rewards1,
R.drawable.rewards2,
R.drawable.rewards3,
R.drawable.rewards4,
R.drawable.rewards5,
R.drawable.rewards6,
};
Integer[] Deactivated ={
R.drawable.rewards1b,
R.drawable.rewards2b,
R.drawable.rewards3b,
R.drawable.rewards4b,
R.drawable.rewards5b,
R.drawable.rewards6b,
};
//for loop that checks to see all the rewards that a particular users has to assign a particular image.
for(int x = 0;x<rewards_num.length;x++)
{
for(int y = 0;y<6;y++)
{
if(rewards_num[x]==y)
{
Images[x]=Activated[y];
}
else
{
Images[x]=Deactivated[y];
}
}
}
return Images;
}
//constructor with the context being passed.
public ImageAdapter(Context m)
{
c = m;
}
public int getCount() {
return 6;
}
public Object getItem(int position) {
return Images[position];
}
public long getItemId(int position) {
return 0;
}
// The function View create a new ImageView for each item that is being referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
finalImages = fillImageArray();
ImageView imageView = new ImageView(c);
imageView.setImageResource(finalImages[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
return imageView;
}
}
finalImages in noi initialized there .........
it is finalImages in the getview which is not get called in 2nd activity (RewardsViewActivity )...........
if possible move this line to constructor finalImages = fillImageArray();

How to mark views in a ListView?

I have an app with a list view. The listview works fine. The problem starts, when I want the list to start with some of the rows marked. I can mark a row, if I press on it. But, don't seem to find a way to mark any row on initialization.
This is my code:
listViewOfBluetooth = getListView();
setInitialEnabledDevices();
listViewOfBluetooth.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String chosenBluetoothDevice = (String) ((TextView) view).getText();
BluetoothEnableOrDisable(view, chosenBluetoothDevice);
Toast.makeText(getApplicationContext(), chosenBluetoothDevice, Toast.LENGTH_SHORT).show();
editor.putString("bluetooth_name_from_list1", chosenBluetoothDevice);
editor.putBoolean("have_the_cars_bluetooth", true);
editor.commit();
Intent intent = new Intent(List.this, ParkOGuardActivity.class);
startActivity(intent);
}
});
}
public static void setInitialEnabledDevices(){
int length = listViewOfBluetooth.getChildCount();
View view = null;
String first = prefs.getString("bluetooth_name_from_list0", "");
String second = prefs.getString("bluetooth_name_from_list1", "");
String third = prefs.getString("bluetooth_name_from_list2", "");
for(int i = 0; i < length; i++){
view = listViewOfBluetooth.getChildAt(i);
if(view.equals(first) || view.equals(second) || view.equals(third)) {
view.setBackgroundColor(Color.GRAY);
}
}
}
How can I fix it?
Thanks!
You can achive this by using custom adapter. Here is the workaround.
Initialize your custom adapter
Add some flag for marked device names.
Override the getView() & check for the flag. And set the background of the list item accordingly.
Reply if you don't get it or face any complexity.
Update:
Here is a sample adapter. I didn't compile the code. So there might be some errors.
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class TestAdapter extends BaseAdapter
{
ArrayList<String> deviceNames;
ArrayList<Boolean> selected;
Context context;
public TestAdapter(Context context)
{
this.context = context;
deviceNames = new ArrayList<String>();
selected = new ArrayList<Boolean>();
}
public void addDeviceToList(String deviceName, boolean isSelected)
{
deviceNames.add(deviceName);
selected.add(isSelected);
notifyDataSetChanged();
}
public int getCount()
{
return deviceNames.size();
}
public Object getItem(int position)
{
return deviceNames.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
TextView tv = new TextView(context);
tv.setText(deviceNames.get(position));
if(selected.get(position) == true)
{
tv.setBackgroundColor(Color.parseColor("#ff0000"));
}
return tv;
}
}
Now create adapter object and set the adapter to listView. And add single item by calling addDeviceToList() method.
That seems to nasty
but i think you want to modify the views inside listview before loading it
The thing is, that your list won't have children as long as the list is not displayed to the user.so you may not modify the view before showing it to the user
But if you really need to communicate with the views on a such low level you could try to attach a scroll listener to your list:
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = 0; i < visibleItemCount; i++) {
View child = getChildAt(i);
Now edit this view
}
}

Categories

Resources