i need help to save the rating of rating bar in my list view for each item.My question is how can i do it because the OnItemClickListener does not work.
this is how my custom array adapter looks like
public class CustomArrayAdapter extends ArrayAdapter<String> {
public ArrayList<String> ratings;
private Activity context;
private int[] imageID;
private String[] stdName;
private double[] GPA;
private String[] course;
private String[] rollNo;
public float cRating;
public CustomArrayAdapter(Activity context, int[] imageID, String[] stdName, double[] GPA, String[] course, String[] rollNo) {
super(context, R.layout.row_design, stdName);
this.context = context;
this.imageID = imageID;
this.stdName = stdName;
this.GPA = GPA;
this.course = course;
this.rollNo = rollNo;
}
static class ViewContainer
{
public ImageView stdImage;
public ImageView possibleImage;
public TextView primaryTV;
public TextView secondryTV;
public RatingBar ratingBar;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = convertView;
if(rowView == null) {
//converting the XML file into view objects
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.row_design, null, true);
viewContainer = new ViewContainer();
//getting the refrence of widgets
viewContainer.stdImage = (ImageView) rowView.findViewById(R.id.student_image);
viewContainer.possibleImage = (ImageView) rowView.findViewById(R.id.possibility_image);
viewContainer.primaryTV = (TextView) rowView.findViewById(R.id.primary_text_view);
viewContainer.secondryTV = (TextView) rowView.findViewById(R.id.secondry_text_view);
viewContainer.ratingBar = (RatingBar) rowView.findViewById(R.id.rating_bar);
rowView.setTag(viewContainer);
} else {
viewContainer = (ViewContainer) rowView.getTag();
viewContainer.ratingBar.setRating(0.0f);
rowView.setBackground(null);
}
viewContainer.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
cRating = rating;
}
});
//setting the possible values to widgets
viewContainer.stdImage.setImageResource(imageID[position]);
viewContainer.primaryTV.setText(stdName[position] + " (GPA:" + GPA[position] + ")");
viewContainer.secondryTV.setText(course[position] + " (RollNo:" + rollNo[position] + ")");
if (GPA[position] < 3.0) {
rowView.setBackgroundResource(android.R.color.holo_red_light);
viewContainer.possibleImage.setImageResource(R.drawable.cross_small);
} else {
viewContainer.possibleImage.setImageResource(R.drawable.tick_small);
}
return rowView;
}
}
and this is my activity where i want to get the rating
public class StudentSelectionActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_selection);
//getting the refrence of list view
ListView listView = (ListView) findViewById(R.id.list);
//creating object of Rating activity to access it's public instances
final MainActivity obj = new MainActivity();
//creating custom adapter
final CustomArrayAdapter adapter = new CustomArrayAdapter(this, obj.imageID, obj.stdName, obj.GPA, obj.course, obj.rollNo);
listView.setAdapter(adapter);
//handling events on click listener of list view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(StudentSelectionActivity.this, "rating = " + adapter.cRating, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_selected_students, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Your setOnItemClickListener did not work for adapter class as you are using another clickable class inside adapter. So one option is to use click listener inside adapter class.
As
rowView.setOnClickListener(new View.onClickListener()
{
//Perform your operation.
});
Create an Entry class. This class holds your attributes, like cRating.
Then extend the CustomArrayAdapter for ArrayAdapter<Entry> instead of ArrayAdapter<String>. Change the constructor to something like this
public CustomArrayAdapter(Context context, int layoutResourceID, List<Entry> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.itemList = listItems;
this.layoutResID = layoutResourceID;
}
In your getView method use
EventDetailEntry item = this.itemList.get(position);
to get the corresponding item. Use this item to set the cRating. Then your onItemClicked method should work as expected. Hope that is clear enough.
Related
I have an a gridView that has items, each item has a name and quantity. When I click the item in the gridView, I would like to add the item and the quantity to a dynamic list view that is in the same activity. If I click on the item a several times, the items quantity in the dynamic listView should be increased (no duplicate items are allowed.) This is my current gridView, I have removed the code that adds and a previous listView that failed and I am having it just toast for now:
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private Activity activity;
public GridviewAdapter(Activity activity, ArrayList<String> listItem, ArrayList<Integer> listPicture) {
super();
this.listItem = listItem;
this.listPicture = listPicture;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView itemPicture;
public TextView itemName;
public TextView itemPrice;
public TextView itemStock;
public TextView itemAvailability;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.item_grid_row,
null);
view.itemName = (TextView)
convertView.findViewById(R.id.itemName);
view.itemPrice = (TextView)
convertView.findViewById(R.id.itemPrice);
view.itemStock = (TextView)
convertView.findViewById(R.id.itemStock);
view.itemAvailability = (TextView)
convertView.findViewById(R.id.itemAvailability);
view.itemPicture = (ImageView)
convertView.findViewById(R.id.itemPicture);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.itemName.setText(listItem.get(position));
// view.itemPicture.setImageDrawable(listItem.get(position));
return convertView;
}
}
this is the code for the checkout fragment where the gridView is clicked.
public class CheckoutFragment extends Fragment {
private CheckoutViewModel checkoutViewModel;
private EditText editText1;
private GridviewAdapter mAdapter;
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private GridView gridView;
DBHelper db;
LinearLayout layout_total, layout_grid;
private Button sum;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_checkout,
container, false);
db = new DBHelper(getActivity());
Display display =
getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
editText1 = (EditText)root.findViewById(R.id.editText1);
editText1.setHeight(height/12);
editText1.setShowSoftInputOnFocus(false);
editText1.setFocusable(false);
editText1.setTextColor(Color.parseColor("#FFFFFF"));
editText1.setHintTextColor(Color.parseColor("#FFFFFF"));
editText1.getBackground().setColorFilter(Color.parseColor("#008577"),
PorterDuff.Mode.SRC_ATOP);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart = new Intent(getActivity(),
CartActivity.class);
startActivity(cart);
}
});
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(getActivity(),db.getAll(),
listPicture);
// Set custom adapter to gridview
gridView = (GridView)root.findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,
long arg3) {
//this is where the grid is clicked and items added to dynamic listView
Toast.makeText(getActivity(),
mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
return root;
}
public void prepareList() {
// listItem = new ArrayList<String>();
db = new DBHelper(getActivity());
List<Item> listItem = new ArrayList<>();
listItem = db.getAllItems(db.ITEMS_TABLE_NAME);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_add_customer:
//startActivity(getActivity(),
NewCustomerActivity.class);
Intent newCustomer = new Intent(getActivity(),
NewCustomerActivity.class);
startActivity(newCustomer);
return true;
/* case R.id.action_add_customer:
return true;*/
default:
return super.onOptionsItemSelected(item);
}
}
}
You need to explain the situation a bit better. For now i assume your problem is that the items are duplicating the second list instead of appending the count. For this there is no
one line solution. What you need to do is once an item is selected in the grid, search if it exists in the second list. In that case update the quantity, otherwise add it to the list. Since your second list is based on a Table , you have to execute 2 queries. One to identify if the item already exists (Select Query) and other to change the value (Insert or Update Query). If i misunderstood please correct me so that i can help you better.
Why don't you return the model class in your GridView getItem(..) method instead of 'String' it should work like this
public class GridviewAdapter extends BaseAdapter
{
ArrayList<GridModel> gridItems;
//Constructor
public GridviewAdapter(Activity activity, ArrayList<GridModel> gridItems) {
super();
this.gridItems = gridItems;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return griditems.size();
}
#Override
public GridModel getItem(int position) {
// TODO Auto-generated method stub
return gridItems.get(position);
}
//...add your getView...
}
//GridModel Should be Like So..
class GridModel {
public String itemPicture;
public String itemName;
public String itemPrice;
public String itemStock;
public String itemAvailability;
//or use private variables with getter-setter methods
}
I have a customlistadapter and i am setting it for my listview. Now I want to remove an item of it. I did something below in the longclick event but it returns and FATAL exception.
projectItemArrayAdapter is the object of my customAdapter class. item is the position of the list.
Object item1 = projectItemArrayAdapter.getItem(item);
projectItemArrayAdapter.remove(item1);
projectItemArrayAdapter.notifyDataSetChanged();
LogCat
09-01 16:07:39.564 3506-3506/com.example.anuradha.tblogin
E/AndroidRuntime﹕ FATAL EXCEPTION: main Process:
com.example.anuradha.tblogin, PID: 3506
java.lang.UnsupportedOperationException at
java.util.AbstractList.remove(AbstractList.java:638) at
java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:75)
at java.util.AbstractCollection.remove(AbstractCollection.java:229)
ProjectAdapter class
public class ProjectAdapter extends ArrayAdapter {
private final Context context;
private final String[] values;
private final String[] titles;
private LayoutInflater inflater;
public ProjectAdapter(Context activity,String[] values,String[] titles)
{
super(activity,R.layout.activity_project_item,values);
//inflater = activity.getWindow().getLayoutInflater();
this.context = activity;
this.values = values;
this.titles = titles;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return inflater.inflate(R.layout.activity_project_item,parent,false);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_project_item, parent, false);
TextView project = (TextView) rowView.findViewById(R.id.projectName);
TextView title = (TextView) rowView.findViewById(R.id.projectTitle);
project.setText(values[position]);
title.setText(titles[position]);
if (position%2!=1)
{
String myHexColor = "#2d07101c";
//project.setBackgroundColor(Color.parseColor(myHexColor));
rowView.setBackgroundColor(Color.parseColor(myHexColor));
}
return rowView;
}
#Override
public void remove(Object object) {
super.remove(object);
}
}
ProjectList class - I assign arrayadapter to my listview
public class ProjectList extends Activity {
private ListView projectListView;
private String[] stringArray ;
private ArrayAdapter projectItemArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project_list);
//Set custom ActionBar Color
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#D6D6D6")));
String[] projectName =
new String[] { "Demo", "Test", "Anu", "QDMS"};
String[] projTitle =
new String[] { "Demo Title", "Test Title", "Anu Title", "QDMS Title"};
projectItemArrayAdapter = new ProjectAdapter(this,projectName,projTitle);
projectListView = (ListView) findViewById(R.id.projectList);
projectListView.setAdapter(projectItemArrayAdapter);
this.showActionBar();
projectListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ProjectList.this,MailActiivty.class);
startActivity(intent);
}
});
projectListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long arg3) {
final int item = position;
AlertDialog.Builder alert = new AlertDialog.Builder(
ProjectList.this);
alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Object item1 = projectItemArrayAdapter.getItemId(item);
projectItemArrayAdapter.remove(item1);
projectItemArrayAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("CANCEL",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alert.show();
return true;
}
});
}
//method to assign custom actionbar
private void showActionBar() {
LayoutInflater inflator = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.cust_actionbar, null);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled (false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setCustomView(v);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_project_list, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Use ArrayList instead of an array. Change the adapter constructor to this.
public ProjectAdapter(Context activity,List<String> values,String[] titles)
{
super(activity,R.layout.activity_project_item,values);
//inflater = activity.getWindow().getLayoutInflater();
this.context = activity;
//change the type of values from String[] to List<String>
this.values = values;
this.titles = titles;
}
Then change implementation of remove method. It should look like this
#Override
public void remove(Object object)
{
//remove the call to super.
values.remove(object);
}
Then change this line
String[] projectName = new String[] { "Demo", "Test", "Anu", "QDMS"};
Create an array list and add these elements to it and then pass the list to the adapter constructor.
Let me know if it works. Cheers :)
I have a custom listView that is empty in first time , from other side i have an activity which contains a product details such as picture, title, model .in this activity there is a button , so when user press this button i want to add the product into my custom listView and shows all the product details there,
my listView is:
public class ListViewShoppingBasketActivity extends Activity {
BaseAdapter adapter;
ArrayList<SingleRow> list;
Context context;
String[] titles;
Bitmap[] images;
String[] descriptions;
TextView title;
TextView description;
ImageView image;
String rowTitles;
String rowDescription;
Bitmap rowImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_shopping_basket_layout);
final ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(new MyAdapter(this));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
if (id == 0) {
} else if (id == 1) {
} else if (id == 2) {
} else if (id == 3) {
} else if (id == 4) {
}
}
});
}
class SingleRow {
String rowTitles;
String rowDescription;
Bitmap rowImage;
public SingleRow(String rowTitles, String rowDescription, Bitmap rowImage) {
this.rowTitles = rowTitles;
this.rowDescription = rowDescription;
this.rowImage = rowImage;
}
}
class MyAdapter extends BaseAdapter {
public MyAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.shopping_basket_listview_row,
viewGroup, false);
title = (TextView) row.findViewById(R.id.textView1);
description = (TextView) row.findViewById(R.id.textView2);
image = (ImageView) row.findViewById(R.id.imageView1);
SingleRow temp = list.get(i);
title.setText(temp.rowTitles);
description.setText(temp.rowDescription);
image.setImageBitmap(temp.rowImage);
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list_view_shopping_basket, menu);
return true;
}
// // **********baraye add kardane item jadid be listview
public void addItems(View v) {
list.add(new SingleRow(rowTitles, rowDescription, rowImage));
adapter.notifyDataSetChanged();
}
}
and this is implementation of my button in other activity
b_add_to_cart = (Button) findViewById(R.id.b_add_to_cart);
b_add_to_cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BarcodeDetailsActivity.this,
ListViewShoppingBasketActivity.class);
intent.putExtra("productID", proId);
intent.putExtra("productModel", proModel);
intent.putExtra("productTitle", proTitle);
intent.putExtra("productPictureUrl", mIcon11);
startActivity(intent);
}
});
my problem is , i dont know how and where i can assign my product details in my listview
You can put the next lines to the code of the ListViewShoppingBasketActivity:
Intent i = getIntent();
if (i.getExtras() != null){
int prodId = i.getExtras().getInt("productID");
....
}
You can put theese to an ArrayList, and use an BaseAdapter (http://developer.android.com/reference/android/widget/BaseAdapter.html) to display the data in the list.
I have created a custom lisview with images and text by using an array adapter. I would like to highlight one of the row manually, but I cannot seem to do this. I have tried using setItemChecked and setSelection(1);. I have made sure to disable touch events by calling listView.setEnabled(false);, as I read that manual selection might not work if touch events are enabled. Any insight into this matter would be greatly appreciated. I have included my source code below.
Main Activity
public class MainActivity extends Activity
{
// GUI
int Update_Frequency = 1000;
double ack = 0;
// Sensor Constants
public static String temperature = "--";
public static String humidity = "--";
public static String lpg = "--";
public static String alcohol = "--";
// Layout
ListView listView;
ItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Interface
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{ids[i] = Integer.toString(i+1);}
this.adapter = new ItemAdapter(this,R.layout.row, ids);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setEnabled(false);
listView.setItemChecked(1, true);
listView.setSelection(1);
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
GUI_Management();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_connect:
break;
case R.id.action_disconnect:
break;
case R.id.action_settings:
break;
case R.id.action_about:
break;
case R.id.action_exit:
break;
default:
break;
}
return true;
}
private void GUI_Management()
{
new Thread()
{
public void run()
{
//Replace with a changeable variable
while (true)
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Thread.sleep(Update_Frequency);
}
catch (InterruptedException e)
{
}
}
}
}.start();
}
}
Array Adapter
public class Model extends MainActivity
{
public static ArrayList<Item> Items;
public static void LoadModel()
{
Items = new ArrayList<Item>();
Items.add(new Item(1, "temperature_icon.png", "Temperature/Humidity " + temperature + "°F / " + humidity + "%"));
Items.add(new Item(2, "gas_icon.png", "LPG " + lpg +" ppm"));
Items.add(new Item(3, "alcohol_icon.png", "Alcohol " + alcohol + " ppm"));
}
public static Item GetbyId(int id)
{
for(Item item : Items)
{
if (item.Id == id)
{
return item;
}
}
return null;
}
}
class Item
{
public int Id;
public String IconFile;
public String Name;
public Item(int id, String iconFile, String name)
{
Id = id;
IconFile = iconFile;
Name = name;
}
}
class ItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] Ids;
private final int rowResourceId;
public ItemAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.Ids = objects;
this.rowResourceId = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
// get input stream
InputStream ims = null;
try {
ims = context.getAssets().open(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
return rowView;
}
}
put setonclick listener in rootview object which are inflate by you in getview method this will solve your issue and on click event you can change the background of rootview and many more you can do with it.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
if (position == selectedItem)
{
rootView /*or you can use any viewgroup*/
.setBackgroundResource(R.drawable.background_dark_blue);
}
else
{
rootView
.setBackgroundResource(R.drawable.border02);
}
return rowView;
}
private int selectedItem;
public void setSelectedItem(int position) {
selectedItem = position;
}
i know this is not good solutionbut might this help you out you can use setSelectedItem method to highlight row
and please use static placeholder class for efficiency and use position field in static placeholder class to get position of selected row
I followed the following tutorial to create a listview that has both an image and text in it. [http://www.debugrelease.com/2013/06/24/android-listview-tutorial-with-images-and-text/
It looks like this..
[http://i.stack.imgur.com/l7ukU.png
I modified it slighlty to contain only three items. What I would like to do is change the text in the listview based on data that I will be receiving over USB. How do I go about changing the data from within my main activity?
Here is the code for my model for the list items...
public class Item
{
public int Id;
public String IconFile;
public String Name;
public Item(int id, String iconFile, String name)
{
Id = id;
IconFile = iconFile;
Name = name;
}
}
Here is the code for my arraylist
public class Model extends Globals
{
public static ArrayList<Item> Items;
public static void LoadModel()
{
Items = new ArrayList<Item>();
Items.add(new Item(1, "alarm.png", "Alarm"));
Items.add(new Item(2, "calc.png", "Calculator"));
Items.add(new Item(3, "play.png", "Play"));
}
public static Item GetbyId(int id)
{
for(Item item : Items)
{
if (item.Id == id)
{
return item;
}
}
return null;
}
}
Here is the code for the custom adapter...
public class ItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] Ids;
private final int rowResourceId;
public ItemAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.Ids = objects;
this.rowResourceId = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
// get input stream
InputStream ims = null;
try {
ims = context.getAssets().open(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
return rowView;
}
And lastly my main activity code...
public class MainActivity extends Globals
{
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{
ids[i] = Integer.toString(i+1);
}
ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Exiting", Toast.LENGTH_SHORT)
.show();
//finish();
break;
default:
break;
}
return true;
}
When you receive data, you need to set adapter again and call notifitydatachange.