Spinner with custom drop-down view not triggering onItemSelected() - android

I have a Spinner that uses a custom adapter where the getDropDownView() is overridden. Each item in the custom drop-down view is made up of a TextView and a Button.
But, when I run my code, the spinner drop-down items display fine, but clicking them does nothing. The spinner drop-down remains open and spinner.onItemSelected() is not triggered.
drop_down_item.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:singleLine="true" />
<Button
android:id="#+id/dropdown_button"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="Remove"/>
</RelativeLayout>
Custom adapter code
public View getDropDownView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.drop_down_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.dropdown_text);
textView.setText(mValues.get(position));
Button buttonView = (Button) rowView.findViewById(R.id.dropdown_button));
return rowView;
}
I create my spinner and adapter with this code:
spinner = (Spinner) findViewById(R.id.my_spinner);
MyAdapter adapter = new MyAdapter(getViewContext(), R.layout.spinner_item, values);
adapter.setDropDownViewResource(R.layout.drop_down_item);
spinner.setAdapter(adapter);
...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// Do something here - but this never runs
}
});
So I don't know why onItemSelected() is no longer called?
I was wondering if I need to put a click listener on the drop-down TextView which should in turn trigger onItemSelected() using maybe spinner.setSelection(pos)?

The Events is basically a interface that Activity implements to recieve the callBack by clicking on the LinearLayout of the DropDown View of Spinner.
public class MyArrayAdapter extends BaseAdapter {
String[] values;
int CustomResource;
Context context;
Events events;
public MyArrayAdapter(Context baseContext, int customspinnerview,
String[] stringArray, Events events) {
values = stringArray;
context = baseContext;
this.events = events;
CustomResource = customspinnerview;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
if (position < values.length)
return values[position];
else {
return null;
}
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (rowView == null) {
rowView = inflater.inflate(CustomResource, parent, false);
}
TextView textView = (TextView) rowView.findViewById(R.id.dropdown_text);
textView.setText(values[position]);
Button button = (Button) rowView.findViewById(R.id.Button_text);
return rowView;
}
#Override
public View getDropDownView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;`enter code here`
if (rowView == null) {
rowView = inflater.inflate(CustomResource, parent, false);
}
final LinearLayout parentRelative = (LinearLayout) rowView
.findViewById(R.id.parent);
final TextView textView = (TextView) rowView
.findViewById(R.id.dropdown_text);
textView.setText(values[position]);
Button button = (Button) rowView.findViewById(R.id.Button_text);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
events.onItemSelectedLister(
(AdapterView<?>) parentRelative.getParent(),
parentRelative, position, (long) 0);
}
});
// Button buttonView = (Button)
// rowView.findViewById(R.id.dropdown_button);
return rowView;
}
Events Inteface Its a interface that the Activity implement in order to recieve the callbacks from the Adapter.
import android.view.View;
import android.widget.AdapterView;
public interface Events {
public void onItemSelectedLister(AdapterView<?> parent, View view,
int position, long id);
}
Activity Implementation.
onItemSelected Implementation is the place where you can do your task.....
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import com.example.adapter.MyArrayAdapter;
public class MainActivity extends Activity implements Events {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new MyArrayAdapter(getBaseContext(),
R.layout.customspinnerview, getResources().getStringArray(
R.array.values), this));
}
#Override
public void onItemSelectedLister(AdapterView<?> parent, View view,
final int position, long id) {
//perform your Task.......
Method method;
try {
method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
try {
method.invoke(spinner);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
spinner.post(new Runnable() {
#Override
public void run() {
spinner.setSelection(position);
spinner.setSelected(true);
((MyArrayAdapter) spinner.getAdapter()).notifyDataSetChanged();
}
});
}
}
Activity xml File for setContentView
<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.customspinner.MainActivity" >
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</Spinner>
</RelativeLayout>
Spinner View which is passed to Adapter as layout file.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#99000000"
android:id="#+id/parent"
android:orientation="horizontal">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/Button_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="remove"/>
</LinearLayout>
the Code works perfectly fine :) .I have the code perfectly running.

Solution is to set android:focusable="false" in the layout for both the TextView and the Button.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:singleLine="true" />
<Button
android:id="#+id/dropdown_button"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:text="Remove"/>
</RelativeLayout>
Alternatively can also do this in the code:
textView.setFocusable(false);
buttonView.setFocusable(false);
Found the answer here. This works because the Spinner implementation only allows one focusable item in the view. That's why I wasn't able to select the item.

Related

Fire a method after selection in a spinner

First of all Happy New Year to everyone!! Second I would like to know if somenone can help me with this problem. I have a ListActivity in which every row has a spinner to select a batch number.
<?xml version="1.0" encoding="utf-8"?>
<com.picking.utils.RelativeLayout
android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayoutPickingRow"
android:layout_width="match_parent"
android:layout_height="70dp"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
>
<LinearLayout
android:id="#+id/linearLayoutPickingRow"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:baselineAligned="false"
android:orientation="horizontal"
android:paddingLeft="10dp"
>
//TextViews and other things
<Spinner
android:id="#+id/spinnerLote"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="40dp"
android:layout_marginTop="5dp"
android:background="#drawable/spinner_bg"
android:focusable="false"
android:spinnerMode="dialog"
android:visibility="visible"
/>
</LinearLayout>
what I want to achive is to "simulate" the onListItemClick method when a bacthnumber is selected
protected void onListItemClick(ListView l, View view, int position, long id)
I have a custom spinner adapter and a custom adapter too for the list with a holder pattern
package com.picking.adapters;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.picking.POJOS.LotesAbiertos;
import com.pickingR;
import java.util.ArrayList;
public class SpinnerCustomAdapter<L> extends ArrayAdapter<LotesAbiertos> {
private ArrayList<LotesAbiertos> list;
private Activity context;
Resources resources;
public SpinnerCustomAdapter(Activity activity, int resource, int textViewResourceId, ArrayList<LotesAbiertos> list) {
super(activity, resource, textViewResourceId, list);
this.list = list;
this.context = activity;
resources = activity.getResources();
}
#Override
public int getCount() {
return list.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.custom_spinner, parent, false);
LotesAbiertos item = list.get(position);
TextView tvLote = (TextView) row.findViewById(android.R.id.text1);
if (item != null) { // Parse the data from each object and set it.
if (item.status.equalsIgnoreCase("2")) {
tvLote.setText("SIN LOTES");
} else {
tvLote.setText(item.loteFormateado);
}
}
return row;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) { // This view starts when we click the spinner.
final int positionRow = position;
View row = convertView;
if (row == null) {
LayoutInflater inflater = context.getLayoutInflater();
row = inflater.inflate(R.layout.custom_spinner_drop, parent, false);
}
TextView tvLote = (TextView) row.findViewById(android.R.id.text1);
TextView tvAcceso = (TextView) row.findViewById(android.R.id.text2);
LotesAbiertos item = list.get(position);
if (item != null) { // Parse the data from each object and set it.
if (position == 0) {
tvLote.setText("Lotes");
row.setBackgroundColor(resources.getColor(R.color.green_ligth));
} else {
if (item.status.equalsIgnoreCase("2")) {
tvLote.setText("SIN LOTES");
} else {
tvLote.setText(item.loteFormateado.substring(0, 5));
Spannable secondWord = new SpannableString(item.loteFormateado.substring(item.loteFormateado.length() - 3));
secondWord.setSpan(new StyleSpan(Typeface.BOLD), 0, secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvLote.append(secondWord);
}
row.setBackgroundColor(resources.getColor(R.color.white));
}
if (item.status.equalsIgnoreCase("0") || item.status.equalsIgnoreCase("2")) {
tvLote.setTextColor(resources.getColor(R.color.green_dark));
tvAcceso.setVisibility(View.INVISIBLE);
} else {
tvLote.setTextColor(resources.getColor(R.color.dark_grey));
tvAcceso.setVisibility(View.VISIBLE);
}
}
return row;
}
}
Considering I have the adapters and the activity in different packages I can`t call the method as it is protected, but I can have a method like this.
public void fireOnListItemClick(View view, int position, long id) {
onListItemClick(getListView(), view, position, id);
}
I can call this method from the spinnner adapter but the question is how I get the
view, position, id
parameters of the row of the listview to pass them to the method? Shoud I have in the spinner adapter a setOnClickListener like this?
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
/*..........*/
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Call fireOnListItemClick*/
}
});
return row;
}
Thanks in advance for you time
Have a look at the OnItemSelectedListener
Example usage
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tv.setText("Spinner selected : ");
tv.setText(tv.getText() + parent.getItemAtPosition(position).toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
//Another interface callback
}
});

changing content of text view on button click inside listview

this is the image of layout tile.xml
i have created a list using custom adapter it has 2 textviews and 2 buttons inside it now what i want is to change the visiblity of one of textview on button click.
I am handling the button clicks outside the custom adapter.I want to toggle visiblity toggle for second textview with id tvstatus using on and off buttons.
this is code for customadapter
package slide.apptech.com.rpiconnect;
/**
* Created by MOHIT on 09-06-2016.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
//custom adapter class extends a arrayadapter
public class customadapter2 extends ArrayAdapter<String> {
private final Context context;
private final ArrayList values;
private String stv = "Ststus";
public customadapter2(Context context, ArrayList values) {
//for super constructor pass
// context files
//layout file required for list
//arraylist that has strings to be displayed
super(context, R.layout.tile, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewGroup par = parent;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.tile, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.tvappname);
Button on = (Button) rowView.findViewById(R.id.bon);
Button off = (Button) rowView.findViewById(R.id.boff);
final TextView status = (TextView) rowView.findViewById(R.id.tvstatus);
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status.setVisibility(View.VISIBLE);
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) ;
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
//get(position method is used to access the elements of arraylist)
String val = (String) values.get(position);
textView.setText(val);
// Change the icon for Windows and iPhone
String s = (String) values.get(position);
return rowView;
}
public void myClickHandler(View v)
{
}
}
this is code for my xml file that i am using as listelement
<?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">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_margin="2dp"
android:layout_height="100dp"
card_view:cardCornerRadius="4dp"
android:layout_alignParentStart="true"
android:background="#611818"
android:paddingBottom="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OFF"
android:id="#+id/boff"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginStart="37dp"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bon"
android:text="ON"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="28dp"
android:focusable="false"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ttile"
android:id="#+id/tvappname"
android:textSize="20sp"
android:layout_above="#+id/boff"
android:layout_centerHorizontal="true"
android:textColor="#color/abc_input_method_navigation_guard" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="#+id/tvstatus"
android:layout_below="#+id/tvappname"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textColor="#060505"
android:visibility="invisible"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
please comment if you want any other file
No, don't do that. Changing the value directly of any view inside listview is a bad idea. Just make changes in your arraylist and then call notifyDataSetChanged() to reflect changes.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final int pos = position;
final ViewGroup par = parent;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.tile, parent, false);
final TextView textView = (TextView) rowView.findViewById(R.id.tvappname);
Button on = (Button) rowView.findViewById(R.id.bon);
Button off = (Button) rowView.findViewById(R.id.boff);
final TextView status = (TextView) rowView.findViewById(R.id.tvstatus);
//get(position method is used to access the elements of arraylist)
String val = (String) values.get(position);
textView.setText(val);
if(val.equalsIgnoreCase("off")){
status.setVisibility(View.INVISIBLE);
}else{
status.setVisibility(View.VISIBLE);
}
on.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.set(position, "On");
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.set(position, "Off");
notifyDataSetChanged();
((ListView) par).performItemClick(v, pos, 0); // Let the event be handled in onItemClick()
}
});
// Change the icon for Windows and iPhone
String s = (String) values.get(position);
return rowView;
}
Hope it will help :)

show/hide button when focus the list item in android listview

Many list items are listed in my listview.
In that list item having 2 buttons and one textview.
Here i have using following code. Now my list showing the edit/delete button.If I have to focus which list item means that item alone have to show edit/delete button.other list item don't need to show the edit/delete button.
How can i do ? Please check it and give me a idea to implement this part ?
stafflist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
Button bPrevious = (Button)view.findViewById(R.id.view_staff);
bPrevious.setVisibility(View.VISIBLE);
Button bPlaying = (Button)view.findViewById(R.id.delete_staff);
bPlaying.setVisibility(View.VISIBLE);
}
});
Now if i have selected any item from that list means it's showing the edit/delete button. after that i have selected any other item from list means that item also showing the edit/delete button with this previous selected item also showing the edit/delete button.
But i want to show the current selected item only need to show edit/delete button ?
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.manager_list_staff, null);
TextView staffname = (TextView)vi.findViewById(R.id.my_staffname);
TextView staff_empcode = (TextView)vi.findViewById(R.id.my_staffempcode);
LinearLayout editdelete = (LinearLayout)vi.findViewById(R.id.edit_delete);
final Button edit_staff = (Button)vi.findViewById(R.id.view_staff);
final Button delete_staff = (Button)vi.findViewById(R.id.delete_staff);
HashMap<String, String> Order = new HashMap<String, String>();
Order = data.get(position);
int temp = parent.getId()+1;
staff_id.setText(Order.get(Manager_List_Staff.TAG_STAFF_ID));
I tested with the below code and its working, you could check with your requirement. The notifyDataSetChanged() method is used to tell the adapter that the arraylist values are changed so please reload the list so now we got the selected item and we will keep it's VISIBLE state to true and others to GONE.
MainActivity
package com.example.test;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemClickListener
{
ListView listview;
testAdapter adp;
ArrayList<String> testvalues=new ArrayList<String>();
public static int selectedValue=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView) findViewById(R.id.listView1);
testvalues.add("India");
testvalues.add("USA");
testvalues.add("Australia");
listview.setOnItemClickListener(this);
adp=new testAdapter();
listview.setAdapter(adp);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Button bPrevious = (Button)arg1.findViewById(R.id.button1);
bPrevious.setVisibility(View.VISIBLE);
Button bPlaying = (Button)arg1.findViewById(R.id.button2);
bPlaying.setVisibility(View.VISIBLE);
selectedValue=arg2;
adp.notifyDataSetChanged();
}
class testAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return testvalues.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return testvalues.get(arg0);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.testing, null);
TextView staffname = (TextView)vi.findViewById(R.id.textView1);
final Button edit_staff = (Button)vi.findViewById(R.id.button1);
final Button delete_staff = (Button)vi.findViewById(R.id.button2);
staffname.setText(testvalues.get(position));
if(selectedValue==position && selectedValue!=-1)
{
edit_staff.setVisibility(View.VISIBLE);
delete_staff.setVisibility(View.VISIBLE);
}
else
{
edit_staff.setVisibility(View.GONE);
delete_staff.setVisibility(View.GONE);
}
return vi;
}
}
}
Main Activity XML Layout File (activity_main.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"
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=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="500dp" >
</ListView>
</RelativeLayout>
Inflate XML Layout File (testing.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
Use member variable to store the button. In my case, I'm using Layout to display some text along with button. So I'm changing the view of the inner layout of list item.
View hiddenLayout;
Attach listener to the listView. Before hiding the view / layout, verify if it is visible or not.
myList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(hiddenLayout != null && hiddenLayout.getVisibility() == View.VISIBLE)
hiddenLayout.setVisibility(View.GONE);
hiddenLayout = view.findViewById(R.id.myTripBbuttonLayout);
hiddenLayout.setVisibility(View.VISIBLE);
}
});
In your onClickItem listener you need to define and find your button. Here is an example:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int btnStart = R.id.btnStart;
int btnDelete = R.id.btnDelete;
//here set all button in item invisible
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).findViewById(btnStart).setVisibility(View.INVISIBLE);
parent.getChildAt(i).findViewById(btnDelete).setVisibility(View.INVISIBLE);
parent.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
//but here we set for selected item buttons visible, and change background view.setBackgroundColor(getResources().getColor(R.color.color_selected_nav_drawer));
view.findViewById(btnStart).setVisibility(View.VISIBLE);
view.findViewById(btnDelete).setVisibility(View.VISIBLE);
}

Get different multiple image views in a list view

I have been trying to implement a list view which has five image views in a single row of a list view. I found that it can be done with layout inflater but since I am new to android I could not exactly get how to make the best use of it. I want to get a view of this sort:
L,S,D,A,E are images and it should change accordingly for different users in the list view according to the data provided dynamically. Can anybody please help me with the code snippet for this, or just give me an idea on how to implement it?
Okay so your list view should inflate a layout of this type:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/layoutContainer" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv1" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv2" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv3" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv4" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv5" />
</LinearLayout>
Save it to row.xml located in your layout folder.
Next implement this in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter myAdapter = new CustomAdapter(getApplicationContext());
ListView mainListView = (ListView) findViewById(R.id.lv);
mainListView.setAdapter(myAdapter);
}
Finally, you need to create the CustomAdapter.java class, like this:
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class CustomAdapter extends BaseAdapter {
private Bitmap[][] data;
private int count;
private Context context;
public CustomAdapter(Context context) {
this.context = context;
data = new Bitmap[100][];
count = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public Bitmap[] getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View adapterView = convertView;
if (adapterView == null) {
adapterView = inflater.inflate(R.layout.row, null);
}
ImageView imageView = (ImageView) adapterView.findViewById(R.id.iv1);
imageView.setImageBitmap(data[position][0]);
//Repeat the last two steps for all five images, changing the last index accordingly
return adapterView;
}
public void addBitmapArray (Bitmap[] newValue) {
data[++count] = newValue;
}
}
In row of the list add a linear layout LinearLayout1 then do something like fallowing in your adapter add dynamically images to the list item..
public View getView(final int position, View convertView, ViewGroup parent)
{
// System.out.println(" inside KeyvalueAdapter..");
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.new_row, null);
holder = new ViewHolder();
holder.tv_title = (TextView) convertView.findViewById(R.id.titleTextView);
ImageView imageView = new ImageView(context);
imageView.setImageResource(resId);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearLayout.addView(imageView);
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
holder.tv_title.setText(notifList.get(position));
return convertView;
}
If you want to load different image you have to extend your listview adapter:
example if i understand correctly your question.
Check out this thread:
Android custom Row Item for ListView
You have to write your own xml with 5 imageviews

GridView and ImageButton Weird issue

Hi all I have custom grid view with imageButton and textView as follows
Here i have used imageButton.. The problem is the grid is not clickable.. But if i use here imageView it works fine but UI is not appropriate.
Here is my layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp"
>
<ImageButton
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/newlocation"
android:background="#drawable/btnbackground"
/>
<TextView
android:id="#+id/SpeakerName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15sp"
android:text="Some Speaker"
/>
Here is my adapter
package com.tt.cc;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SavedConferencesGridAdapter extends ArrayAdapter<String>{
Context mContext;
List<String> confernceList;
public SavedConferencesGridAdapter(Context context, int textViewResourceId, List<String> confernceList)
{
super(context,textViewResourceId,confernceList);
this.confernceList = confernceList;
this.mContext = context;
Log.e("TAG", confernceList.size()+"");
}
int[] picIds = new int[] { R.drawable.newschedule,R.drawable.newexhibitors,
R.drawable.newsponsers, R.drawable.newlocation,
R.drawable.newfavourites, R.drawable.newreminder,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info };
#Override
public int getCount() {
// TODO Auto-generated method stub
return confernceList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.entity, null);
TextView tv = (TextView)v.findViewById(R.id.SpeakerName);
tv.setText("tt");
/*ImageView iv = (ImageView) v.findViewById(R.id.profilePic);
iv.setImageResource(picIds[position]);*/
}
else
{
v = convertView;
}
return v;
}
}
and here is my activity
public class SavedConferencesActivity extends Activity{
GridView confereneceGridView;
ArrayAdapter<String> conferneceAdapter;
Button btnUpdate;
List<String> conferenceList;
TextView txtHeading;
Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.homegridlayout);
initialize();
confereneceGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SavedConferencesActivity.this, conferenceList.get(position)+"", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
conferneceAdapter = new SavedConferencesGridAdapter(this, android.R.layout.simple_list_item_1, conferenceList);
confereneceGridView.setAdapter(conferneceAdapter);
}
private void initialize() {
confereneceGridView = (GridView) findViewById(R.id.gridOfConference);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
txtHeading = (TextView) findViewById(R.id.txtTag);
conferenceList = new ArrayList<String>();
conferenceList.add("AA");
conferenceList.add("BB");
conferenceList.add("CC");
if (conferenceList.size() == 0)
txtHeading.setText("No conferences saved");
else
txtHeading.setText("Selected Conferences");
}
}
Please help me in solving this problem. Or if any alternative available..
Simple. Provide this attribute for the ImageButton ,
android:focusable="false"
This problem usually occurs when there is a focussable element in the Grid.(Eg:Buttons, ImageButton etc).
Reason of this ImageButton is by Default is clickable and focusable, so Focus and click event never goes to ItemView.
Set Properties
android:focusable-"false"
and
android:clickable="false"
Your item's Layout should be:
<LinearLayout ...
android:descendantFocusability="blocksDescendants">
<ImageButton ...
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
Don't forget setOnClickListener for ImageButton in Adapter.
in your adapter class,
before you return the view "v", add the "onClickListener" to "v"
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position, Toast.LENGTH_SHORT).show();
}
});

Categories

Resources