I'm trying to do a ListView that it can refresh when i call the function actualizarDisplay().
I've seen in the log cat a message, and i have doubts abaout that message:
10-06 12:24:02.524: I/dalvikvm(6911): Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
10-06 12:24:02.524: W/dalvikvm(6911): VFY: unable to resolve virtual method 561: Landroid/content/res/TypedArray;.getType (I)I
10-06 12:24:02.524: D/dalvikvm(6911): VFY: replacing opcode 0x6e at 0x0002
10-06 12:24:02.688: D/AbsListView(6911): Get MotionRecognitionManager
10-06 12:24:02.712: D/AbsListView(6911): onVisibilityChanged() is called, visibility : 4
10-06 12:24:02.712: D/AbsListView(6911): unregisterIRListener() is called
10-06 12:24:02.712: D/AbsListView(6911): onVisibilityChanged() is called, visibility : 0
10-06 12:24:03.055: D/AbsListView(6911): unregisterIRListener() is called
my problem is when i push the screen the event onClickListener is not reviced.
This is my main activity:
public class Rescate extends ActionBarActivity {
ArrayList<Ficha> listaFichas = new ArrayList<Ficha>();
MyCustomAdapter dataAdapter = null;
Ficha fichaAux = new Ficha();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rescate);
Bundle b = this.getIntent().getExtras();
int tipo=b.getInt("lugar");
switch(tipo) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
fichaAux.setNumInv("1");
fichaAux.setIden("cuadro");
fichaAux.setUbi("sacrsitía");
fichaAux.setNumHom(2);
fichaAux.setMat("Plástico");
fichaAux.setEstado(0);
fichaAux.setPrioridad(1);
listaFichas.add(fichaAux);
fichaAux = new Ficha();
fichaAux.setNumInv("2");
fichaAux.setIden("cuadro");
fichaAux.setUbi("sacrsitía");
fichaAux.setNumHom(2);
fichaAux.setMat("Plástico");
fichaAux.setEstado(0);
fichaAux.setPrioridad(2);
listaFichas.add(fichaAux);
actualizarDisplay();
break;
default:
setContentView(R.layout.activity_rescate);
}
}
this is my function actualizarDisplay which implements the lsiteners:
public void actualizarDisplay()
{
dataAdapter = new MyCustomAdapter(this,R.layout.listadofichas, listaFichas);
ListView listView = (ListView) findViewById(R.id.listaObras);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Intent passIntent = new Intent();
passIntent.setClass(Rescate.this, VistaFicha.class);
Bundle bundle = new Bundle();
bundle.putCharSequence("num",listaFichas.get(arg2).getNumInv() );
bundle.putCharSequence("ubicacion",listaFichas.get(arg2).getUbi() );
passIntent.putExtras(bundle);
startActivity(passIntent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3)
{
final String[] opciones = new String[] { "Si", "No"};
final AlertDialog.Builder dialogo = new AlertDialog.Builder(Rescate.this);
dialogo.setCancelable(true);
dialogo.setTitle("¿Desea establecer que la obra ha sido rescatada?");
dialogo.setItems(opciones, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0)
{
listaFichas.get(arg2).setEstado(1);
actualizarDisplay();
}
else
{
listaFichas.get(arg2).setEstado(0);
actualizarDisplay();
}
}
});
dialogo.setCancelable(false);
dialogo.create();
dialogo.show();
return false;
}
});
listView.setAdapter(dataAdapter);
}
and this are my functions to handle the ListView:
public class FichaAdapter extends BaseAdapter
{
private ArrayList<Ficha> fichas;
public FichaAdapter(ArrayList<Ficha> fichas)
{
this.fichas = fichas;
//Cada vez que cambiamos los elementos debemos noficarlo
notifyDataSetChanged();
}
public int getCount()
{
return fichas.size();
}
public Object getItem(int position)
{
return fichas.get(position);
}
public long getItemId(int position)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
FichaView view;
if (convertView == null) //NO existe, creamos uno
view = new FichaView(parent.getContext());
else //Existe, reutilizamos
view = (FichaView) convertView;
view.setFicha(fichas.get(position));
return view;
}
}
private class MyCustomAdapter extends ArrayAdapter<Ficha>
{
private ArrayList<Ficha> fichaList;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<Ficha> fichaList)
{
super(context, textViewResourceId,fichaList);
this.fichaList = new ArrayList<Ficha>();
this.fichaList.addAll(fichaList);
}
private class ViewHolder
{
TextView num,iden,ubi,hombres,material;
ImageView foto;
RelativeLayout fondo;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listadofichas, null);
holder = new ViewHolder();
holder.num = (TextView) convertView.findViewById(R.id.numInvResCon);
holder.iden = (TextView) convertView.findViewById(R.id.idenRescCont);
holder.ubi = (TextView) convertView.findViewById(R.id.ubiResCon);
holder.hombres = (TextView) convertView.findViewById(R.id.numHomResCon);
holder.material = (TextView) convertView.findViewById(R.id.matRescCon);
holder.foto = (ImageView) convertView.findViewById(R.id.imaResc);
holder.fondo = (RelativeLayout) convertView.findViewById(R.id.fondoRes);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Ficha ficha = fichaList.get(position);
holder.num.setText(ficha.getNumInv());
holder.iden.setText(ficha.getIden());
holder.ubi.setText(ficha.getUbi());
holder.hombres.setText(String.valueOf(ficha.getNumHom()));
holder.material.setText(ficha.getMat());
if(ficha.getPrioridad()==1)
{
holder.num.setTextColor(Color.RED);
holder.iden.setTextColor(Color.RED);
holder.ubi.setTextColor(Color.RED);
holder.hombres.setTextColor(Color.RED);
holder.material.setTextColor(Color.RED);
}
if(ficha.getPrioridad()==2)
{
holder.num.setTextColor(Color.parseColor("#FF8000"));
holder.iden.setTextColor(Color.parseColor("#FF8000"));
holder.ubi.setTextColor(Color.parseColor("#FF8000"));
holder.hombres.setTextColor(Color.parseColor("#FF8000"));
holder.material.setTextColor(Color.parseColor("#FF8000"));
}
if(ficha.getPrioridad()==3)
{
holder.num.setTextColor(Color.GREEN);
holder.iden.setTextColor(Color.GREEN);
holder.ubi.setTextColor(Color.GREEN);
holder.hombres.setTextColor(Color.GREEN);
holder.material.setTextColor(Color.GREEN);
}
if(ficha.getEstado()== 1)
{
holder.fondo.setBackgroundColor(Color.GREEN);
holder.num.setTextColor(Color.WHITE);
holder.iden.setTextColor(Color.WHITE);
holder.ubi.setTextColor(Color.WHITE);
holder.hombres.setTextColor(Color.WHITE);
holder.material.setTextColor(Color.WHITE);
}
return convertView;
}
}
I think the prgoblem is when the log cat says visibility: 0
I have a warning in this line:
convertView = vi.inflate(R.layout.listadofichas, null);
i think that the problem is here.
i write the layouts:
listadofichas.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fondoRes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:contentDescription="#string/par" >
<ImageView
android:id="#+id/imaResc"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="40dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="1dp"
android:contentDescription="#string/vacia"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/numInv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imaResc"
android:layout_marginLeft="100dp"
android:layout_toRightOf="#+id/imaResc"
android:text="#string/numInvResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/idenResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/numInv"
android:layout_below="#+id/numInv"
android:layout_marginTop="12dp"
android:text="#string/idenResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/ubiResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/idenResc"
android:layout_below="#+id/idenResc"
android:layout_marginTop="12dp"
android:text="#string/ubiResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numHomResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ubiResc"
android:layout_below="#+id/ubiResc"
android:layout_marginTop="12dp"
android:text="#string/numHomResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/matResc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/numHomResc"
android:layout_below="#+id/numHomResc"
android:layout_marginTop="12dp"
android:text="#string/matResc"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numInvResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/idenResc"
android:layout_marginLeft="84dp"
android:layout_toRightOf="#+id/numInv"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/idenRescCont"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/idenResc"
android:layout_alignLeft="#+id/numInvResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/ubiResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/numHomResc"
android:layout_alignLeft="#+id/idenRescCont"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/numHomResCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/matResc"
android:layout_alignLeft="#+id/ubiResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<TextView
android:id="#+id/matRescCon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/matResc"
android:layout_alignBottom="#+id/matResc"
android:layout_alignLeft="#+id/numHomResCon"
android:text="#string/vacia"
android:textSize="#dimen/letrasPequenasAumen" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imaResc"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:layout_toEndOf="#+id/imaResc"
android:layout_toRightOf="#+id/imaResc"
android:contentDescription="#string/guia"
android:src="#drawable/barralat" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/matResc"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:src="#drawable/barrahor" />
<Spinner
android:id="#+id/spinner2"
style="#style/mySpinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/spinner1"
android:layout_below="#+id/spinner1"
android:layout_marginTop="13dp"
android:entries="#array/equipos" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/numInvResCon"
android:layout_alignBottom="#+id/numInvResCon"
android:layout_marginLeft="203dp"
android:layout_toRightOf="#+id/numInvResCon"
android:text="#string/equiposAsig"
android:textColor="#000000"
android:textSize="#dimen/letrasPequenasAumen" />
<Spinner
android:id="#+id/spinner1"
style="#style/mySpinnerItemStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="13dp"
android:layout_marginLeft="13dp"
android:entries="#array/equipos" />
</RelativeLayout>
and the layout of the activity
<LinearLayout 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:background="#FFFFFF"
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="app.gepv.Rescate" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF" >
<ListView
android:id="#+id/listaObras"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="60dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="20dp"
tools:listitem="#layout/listadofichas" >
</ListView>
</RelativeLayout>
</LinearLayout>
The adpater works well because i can change the color,.. but the listener doesn't work
Can anyone help me?
In onCreate of your activity you have a switch in which you initiate the Adapters only if the value tipo is 4, so if it is not, the listview has no adapter and will do nothing. You could either debug to see which value it gets or at least put the line
Log.d("Rescate","tipo = "+tipo)
to see which value it has. To see if the onItemClick is called you could plug as the first line in onItemClick the line:
Log.d("Rescate","onItemClick")
And see if this appears in the Log when you click an item in the list.
I think the error might be related to the fact that ActionBarActivity is depreciated, you should use AppCompatActivity.
If it still doesnt work could you also post the layout files you use?
So here's my code with String list items instead of Ficha ones. I made 'Rescate.java' first extend AppCompatActivity and then ActionBarActivity, and it worked for both versions:
public class Rescate extends ActionBarActivity
{
ArrayList<String> listaFichas = new ArrayList<>();
MyCustomAdapter dataAdapter = null;
String fichaAux = "Hello";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setting this up with Strings to keep things simple
listaFichas.add("Hello");
listaFichas.add("Hi there");
actualizarDisplay();
}
public void actualizarDisplay()
{
dataAdapter = new MyCustomAdapter(this,R.layout.listadofichas, listaFichas);
ListView listView = (ListView) findViewById(R.id.listaObras);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Intent passIntent = new Intent();
passIntent.setClass(Rescate.this, VistaFicha.class);
startActivity(passIntent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3)
{
final String[] opciones = new String[]{"Si", "No"};
final AlertDialog.Builder dialogo = new AlertDialog.Builder(Rescate.this);
dialogo.setCancelable(true);
dialogo.setTitle("¿Desea establecer que la obra ha sido rescatada?");
dialogo.setItems(opciones, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
if (item == 0)
{
actualizarDisplay();
Toast.makeText(Rescate.this, "item = 0", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Rescate.this, "item != 0", Toast.LENGTH_SHORT).show();
}
}
});
dialogo.setCancelable(false);
dialogo.create();
dialogo.show();
return false;
}
});
listView.setAdapter(dataAdapter);
}
}
'VistaFicha.java' is just a blank activity showing "Hello World".
I put the adpater in a separate file 'MyCustomAdapter.java'
public class MyCustomAdapter extends ArrayAdapter
{
private ArrayList<String> fichaList;
private LayoutInflater vi;
public MyCustomAdapter(Context context, int textViewResourceId,ArrayList<String> fichaList)
{
super(context, textViewResourceId,fichaList);
this.fichaList = new ArrayList<String>();
this.fichaList.addAll(fichaList);
// I had to change the original code because my adapter is not an inner class:
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private class ViewHolder
{
TextView num;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
convertView = vi.inflate(R.layout.listadofichas, null);
holder = new ViewHolder();
holder.num = (TextView) convertView.findViewById(R.id.tvHallo);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
String ficha = fichaList.get(position);
holder.num.setText(ficha);
return convertView;
}
}
The xml for the list rows is simply a TextView (R.id.tvHallo) inside a LinearLayout and my Rescate activity contains only the usual "Hello World" and the ListView (R.id.listaObras)
Hope this helps, and let me know if there are any questions :)
Related
I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.
The picture shows that the spinner is in blank when the activity load
When I clicked the arrow it shows the items
but when I choose one, nothing happends.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.Inspeccion.DatosGeneralesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
>
<TextView
android:id="#+id/tvSubestacionTitulo"
android:layout_below="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strSubestacion"
android:textSize="18sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
/>
<TextView
android:id="#+id/tvSubestacionDato"
android:layout_below="#+id/tvSubestacionTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Prueba"
/>
<Spinner
android:id="#+id/spinnerSubEstacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvSubestacionDato"
>
</Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is the Layout of the activity.
<?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="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tvNumeroOpcion"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="1"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDescriptionOption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Guatemala"
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
That is the custom layout for the spinner
Public class ComboAdapter extends BaseAdapter{
private List<Combo> combos;
private Activity activity;
private LayoutInflater inflater;
public ComboAdapter(List<Combo> combos, Activity activity) {
this.combos = combos;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return combos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, null);
TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);
tvId.setText(combos.get(position).getId());
tvDescripcion.setText(combos.get(position).getDescripcion());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getView(position, convertView,parent);
}
}
That is my Adapter
And below is my activity.
public class DatosGeneralesActivity extends AppCompatActivity {
private TextView tvSubestacionDato;
private List<Combo> listaCombo;
private Spinner spinnerSubestacion;
private ArrayAdapter<Combo> adapterSubestacion;
String seleccion;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_generales);
//Inicializando textos
tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);
//Inicializanco listas
listaCombo = new ArrayList<>();
//Inivializando spinners
spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);
AppService service = API.getCombos().create(AppService.class);
Call<List<Combo>> subestacionCall = service.getSubestacion();
subestacionCall.enqueue(new Callback<List<Combo>>() {
#Override
public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
listaCombo.clear();
listaCombo.addAll(response.body());
}
#Override
public void onFailure(Call<List<Combo>> call, Throwable t) {
}
});
//final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
spinnerSubestacion.setAdapter(adapter);
spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Try this changes:
Call adapter like:
ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
now in adapter class:
public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){
super(context,resouceId,textviewId, list);
this.combos = list;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also inside your getView() method inflate layout like:
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, parent , false);
I have been stuck on this problem for almost a day now and have tried numerous previous posts on Stack Overflow, online tutorials etc. but nothing seems to work in my case. I have tried setting focusable, focusable in touch and clickable to false for all textviews in each row list item, set android:descendantFocusability="blocksDescendants" in the Relative Layout for list_item_main.xml but nothing has worked. Any help will really be appreciated! Thanks The setup is as follows:
tab.xml (Layout for listview):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="400dp"
android:clickable="true"
android:id="#+id/android:list"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</LinearLayout>
list_item_main.xml (Each row item):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rLayout">
<TextView
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="XYZ"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#808080"
android:layout_above="#+id/weight"
android:layout_alignLeft="#+id/Qty"
android:layout_alignStart="#+id/Qty"/>
<TextView
android:id="#+id/Qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="150"
android:textSize="18sp"
android:textColor="#808080"
android:layout_marginLeft="39dp"
android:layout_marginStart="39dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="87dp"/>
<TextView
android:id="#+id/dateTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="4"
android:text="Available from: "
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Date"
android:layout_alignLeft="#+id/Qty"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=" 0.000"
android:textStyle="bold"
android:textSize="24sp"
android:id="#+id/Rate"
android:textColor="#808080"
android:layout_alignTop="#+id/Name"
android:layout_toRightOf="#+id/Date"
android:layout_toEndOf="#+id/Date"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="14/08/2007"
android:textSize="18sp"
android:id="#+id/Date"
android:textColor="#808080"
android:layout_below="#+id/weight"
android:layout_toRightOf="#+id/dateTitle"
android:layout_toEndOf="#+id/dateTitle"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=" Kgs"
android:id="#+id/weight"
android:textSize="18sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Qty"
android:layout_alignRight="#+id/Name"
android:layout_alignEnd="#+id/Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="INR"
android:id="#+id/currency"
android:textStyle="bold"
android:textSize="24sp"
android:textColor="#808080"
android:layout_alignTop="#+id/Rate"
android:layout_toRightOf="#+id/Rate"
android:layout_toEndOf="#+id/Rate"/>
DealAdapter:
public class DealAdapter extends ArrayAdapter<Offer2SaleTransaction> {
private List<Offer2SaleTransaction> activeDeals;
private Context context;
private static final Logger logger = Logger.getLogger(DealAdapter.class.getName());
public DealAdapter(List<Offer2SaleTransaction> activeDeals, Context ctx) {
super(ctx, R.layout.list_item_main, activeDeals);
this.activeDeals = activeDeals;
this.context = ctx;
}
public int getCount() {
if (activeDeals != null)
return activeDeals.size();
return 0;
}
public Offer2SaleTransaction getItem(int position) {
if (activeDeals != null)
return activeDeals.get(position);
return null;
}
public long getItemId(int position) {
if (activeDeals != null)
return activeDeals.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item_main, null);
}
Offer2SaleTransaction deal = activeDeals.get(position);
TextView textName = (TextView) v.findViewById(R.id.Name);
textName.setText(deal.getName());
TextView textQty = (TextView) v.findViewById(R.id.Qty);
textQty.setText(Float.toString(deal.getQty()));
// Hardcoded date as of now
TextView textDate = (TextView) v.findViewById(R.id.Date);
textDate.setText("01-01-1994");
logger.info("This is something I want to know " + deal.getSaleDate());
TextView textPrice = (TextView) v.findViewById(R.id.Rate);
textPrice.setText(Float.toString(deal.getRate()));
return v;
}
public List<Offer2SaleTransaction> getActiveDeals() {
return activeDeals;
}
public void setActiveDeals(List<Offer2SaleTransaction> activeDeals) {
this.activeDeals = activeDeals;
}}
Finally, the fragment to display the listview:
public class StatusFragment extends ListFragment implements OnItemClickListener{
DealAdapter adpt;
ListView lView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tab, container, false);
adpt = new DealAdapter(new ArrayList<Offer2SaleTransaction>(), getActivity());
lView = (ListView) view.findViewById(android.R.id.list);
lView.setAdapter(adpt);
lView.setOnItemClickListener(this);
// Exec async load task
new EndpointsStatusAsyncTask().execute(new Pair<Context, String>(getActivity(), "XXXXXX"));
return view;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();
}
private class EndpointsStatusAsyncTask extends AsyncTask<Pair<Context, String>, Void, List<Offer2SaleTransaction>> {
private Offer2SaleTransactionApi myApiService = null;
private final Logger logger = Logger.getLogger(EndpointsStatusAsyncTask.class.getName());
private Context context;
private String TAG = "Background";
#Override
protected List<Offer2SaleTransaction> doInBackground(Pair<Context, String>... params) {
if(myApiService == null) { // Only do this once
Offer2SaleTransactionApi.Builder builder = new Offer2SaleTransactionApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl("https:xxxx");
myApiService = builder.build();
}
context = params[0].first;
String userID = params[0].second;
try {
return myApiService.getOffer2SaleTransaction(userID).execute().getItems();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(List<Offer2SaleTransaction> result) {
if (result == null)
{
Toast.makeText(context, "It didn't work", Toast.LENGTH_LONG).show();
logger.info("Failure in connecting to execute onPostExecute");
}
else
{
super.onPostExecute(result);
adpt.setActiveDeals(result);
adpt.notifyDataSetChanged();
}
}
}}
since you are extending ListFragment, you have to override onListItemClick, and use it in place of onItemClick.
Remove implements OnItemClickListener
Remove lView.setOnItemClickListener(this);
Delete onItemClick
Then
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), "PLEASE WORK",Toast.LENGTH_LONG).show();k(l, v, position, id);
}
I have a listview that contains the list of all my users. Every item from the list is a layout that has a button to show an AlertDialog to change the value of the label of the button. How can I dynamically add an on click event to that button that is generated by the listview Adapter?
This is my adapter:
public class PerfilAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
List<PerfilBean> listaPerfiles = new ArrayList<PerfilBean>();
public Settings01 set=new Settings01();
public PerfilAdapter(Context context,List<PerfilBean> lista) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listaPerfiles=lista;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listaPerfiles.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listaPerfiles.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RelativeLayout itemView;
if (convertView == null) {
itemView = (RelativeLayout) mLayoutInflater.inflate(
R.layout.item_perfil, parent, false);
} else {
itemView = (RelativeLayout) convertView;
}
// obtengo los valores de la vista
Button moneda = (Button) itemView.findViewById(R.id.Moneda);
TextView titulo = (TextView) itemView.findViewById(R.id.Titulo);
TextView nombredesc = (TextView) itemView.findViewById(R.id.txtNombre);
TextView descripcion = (TextView) itemView.findViewById(R.id.txtDescripcion);
String nombreM = Metodos.monedas[listaPerfiles.get(position).getPerfil_tipoMoneda()];
moneda.setText(nombreM);
titulo.setText(listaPerfiles.get(position).getPerfil_nombre());
nombredesc.setText(listaPerfiles.get(position).getPerfil_nombreSec());
descripcion.setText(listaPerfiles.get(position).getPerfil_texto());
return itemView;
}
// metodo parahacer la vista de la celda
public void actualizaDatosLista(List<PerfilBean> listaPerfilesM) {
for(int i=0;i<listaPerfilesM.size();i++){
Log.d("ITEM "+i,listaPerfilesM.get(i).getPerfil_nombreSec());
}
listaPerfiles = listaPerfilesM;
notifyDataSetChanged();
}}
and this is my Activity:
public class Settings01 extends Activity implements OnClickListener {
private List<PerfilBean> lst;
private PerfilDAO perfildao;
private PerfilAdapter perfiladapter;
private ListView lstPerfiles;
public void changeMoneda(final int position) {
int x = 0;
AlertDialog.Builder builder = new AlertDialog.Builder(Settings01.this);
builder.setTitle("Seleccione Tipo de Distribuidor");
builder.setItems(R.array.moneda, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
lst.get(position).setPerfil_tipoMoneda(item);
perfiladapter = new PerfilAdapter(getApplicationContext(), lst);
lstPerfiles.setAdapter(perfiladapter);
dialog.dismiss();
}
});
builder.create();
builder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings01);
lstPerfiles = (ListView) findViewById(R.id.lstSettings);
perfildao = new PerfilDAOImplDB(Settings01.this);
lst = new ArrayList<PerfilBean>();
lst = perfildao.getAll();
perfiladapter = new PerfilAdapter(getApplicationContext(), lst);
Log.d("Info", "En Settings");
lstPerfiles.setAdapter(perfiladapter);
}
#Override
public void onClick(View v) {
Log.d("Info", "derp" + v.getId());
}}
This is the layout that my adapter is currently using:
<?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" >
<TextView
android:id="#+id/Titulo"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="150dp"
android:gravity="left|center_vertical"
android:textColor="#color/Negro"
android:text="derp" />
<TextView
android:id="#+id/lblTipoMoneda"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/Moneda"
android:gravity="left|center_vertical"
android:text="Tipo de moneda: " />
<Button
android:id="#+id/Moneda"
android:layout_width="160dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:gravity="left|center_vertical"
android:background="#color/Blanco"
android:textColor="#color/Negro"
android:text="Peso argentino" />
<ImageView
android:id="#+id/Separador"
android:layout_width="match_parent"
android:layout_height="2.5dp"
android:layout_below="#+id/Moneda"
android:layout_marginLeft="150dp"
android:layout_marginRight="150dp"
android:background="#color/Negro" />
<TextView
android:id="#+id/Nombre"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Separador"
android:layout_marginLeft="150dp"
android:layout_marginTop="10dp"
android:clickable="true"
android:gravity="left|center_vertical"
android:onClick="changeMoneda"
android:text="Nombre :" />
<EditText
android:id="#+id/txtNombre"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_below="#+id/Separador"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Nombre"
android:background="#drawable/fondotxt"
android:textColor="#color/Negro"
android:inputType="text" />
<TextView
android:id="#+id/lblTitulo"
android:layout_width="360dp"
android:layout_height="24dp"
android:layout_below="#+id/txtNombre"
android:layout_marginTop="10dp" />
<EditText
android:id="#+id/txtDescripcion"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="#+id/lblTitulo"
android:layout_marginLeft="150dp"
android:layout_marginRight="150dp"
android:textColor="#color/Negro"
android:gravity="left|center_vertical" />
<ImageView
android:id="#+id/imgPicturefantes"
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_below="#+id/txtDescripcion"
android:layout_toLeftOf="#+id/lblFotoAntes"
android:src="#drawable/what" />
<ImageView
android:id="#+id/imgPicturefdespues"
android:layout_width="100dp"
android:layout_height="150dp"
android:layout_below="#+id/txtDescripcion"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/centerPoint"
android:src="#drawable/what" />
<TextView
android:id="#+id/lblFotoDespues"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_below="#+id/txtDescripcion"
android:layout_marginTop="50dp"
android:layout_toRightOf="#+id/imgPicturefdespues"
android:gravity="center"
android:text="Foto despues: "
android:textSize="18sp" />
<ImageButton
android:id="#+id/btnDespuesF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/btnAntesF"
android:layout_toRightOf="#+id/imgPicturefdespues"
android:background="#drawable/btnupload" />
<TextView
android:id="#+id/centerPoint"
android:layout_width="2dp"
android:layout_height="2dp"
android:layout_below="#+id/txtDescripcion"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/lblFotoAntes"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_below="#+id/txtDescripcion"
android:layout_marginRight="50dp"
android:layout_marginTop="50dp"
android:layout_toLeftOf="#+id/centerPoint"
android:gravity="center"
android:text="Foto antes: "
android:textSize="18sp" />
<ImageButton
android:id="#+id/btnAntesF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/lblFotoAntes"
android:layout_marginRight="75dp"
android:layout_toLeftOf="#+id/centerPoint"
android:background="#drawable/btnupload" />
You can do so in the getView() method of your adapter. For that you will need to use a custom adapter (if you are not doing that already). It will be better if you can show the relevant portions of your code.
EDIT:
The dialog will be shown by your activity. So you can create an interface for listening to this button click event.
public interface BtnClickListener {
public abstract void onBtnClick(int position);
}
Let your custom adapter receive it as input.
private BtnClickListener mClickListener = null;
public PerfilAdapter(Context context, List<PerfilBean> lista, BtnClickListener listener) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listaPerfiles=lista;
mClickListener = listener;
}
Now you can simply set the normal onClickListener in getView() as below
Button moneda = (Button) itemView.findViewById(R.id.Moneda);
moneda.setTag(position); //For passing the list item index
moneda.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mClickListener != null)
mClickListener.onBtnClick((Integer) v.getTag());
}
});
Let your activity pass the required BtnClickListener as part of adapter creation.
perfiladapter = new PerfilAdapter(getApplicationContext(), lst, new BtnClickListener() {
#Override
public void onBtnClick(int position) {
// TODO Auto-generated method stub
// Call your function which creates and shows the dialog here
changeMoneda(position);
}
});
Assuming that lst.get(position).setPerfil_tipoMoneda(item); changes the text which will be used as button text correctly, you should simply call perfiladapter.notifyDataSetChanged() in the onClick of your dialog (Currently you are creating the adapter again which is not required).
public void onClick(DialogInterface dialog, int item) {
lst.get(position).setPerfil_tipoMoneda(item);
perfiladapter.notifyDataSetChanged();
dialog.dismiss();
}
Hope it will work as you expect it to.
In my case i had to add this attribute in the listView :
<ListView
...
android:clickable="true"
...
</ListView>
And in the adapter just add on click listener in the button view.
wrapper.getButtonHi().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DebugUtils.logDebug("Clickeado :: "+ mContact.getUserId());
}
});
Its important to set final the variables:
public View getRowView(final int position, View convertView, ViewGroup parent) {
final BrowseContactItemWrapper wrapper;
final UserModel mContact = lstContact.get(position);
.....
}
Just a small tweak to refresh the renderer from outside.
final FinalMenuListAdapter adapter = this;
viewHolder.deleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mClickListener != null)
mClickListener.onBtnClick((MenuItemObject)v.getTag(),adapter);
}
});
final MenuItemObject menuItemObject = getItem(position);
viewHolder.deleteItem.setTag(menuItemObject);
I couldn't select an item on ListView. I use Custom Adapter to set content of ListView. I have set OnItemClickListener of ListView. However, it didn't respond. I appriciate your help. Here is my code:
List Item (connections.xml):
<?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="wrap_content"
android:orientation="horizontal"
android:padding="6dip" >
<LinearLayout
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:orientation="vertical" >
<TextView
android:id="#+id/connname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/acc1" />
<TextView
android:id="#+id/conntype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="9sp"
android:text="#string/acctype1" />
</LinearLayout>
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The screen which containt ListView (groupconnections.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:orientation="vertical"
android:id="#+id/textOperLayout">
<TextView
android:id="#+id/connectionsLabel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/connections"
android:textColor="#color/conn_text"
android:textSize="25sp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:background="#color/conn_back"/>
<EditText
android:id="#+id/searchEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="#string/searchhint"
android:layout_marginTop="10dp"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dip"
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_above="#+id/textOperLayout"
android:id="#+id/listviewlayout">
<ListView
android:id="#+id/connectionlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:choiceMode="singleChoice" />
</LinearLayout>
<Button
android:id="#+id/addConnCommitButton"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:text="#string/commitToAdd" />
</RelativeLayout>
The related activity (AddMoreConnections.xml):
public class AddMoreConnections extends Activity implements OnItemClickListener{
private ListView mainListView ;
private ArrayAdapter<AbstractHolder> listAdapter ;
private TextView searchConnTextView;
private Button commitButton;
private ArrayList<AbstractHolder> connlist;
private ArrayList<AbstractHolder> listNotOnView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Generate list View from ArrayLis
setContentView(R.layout.groupconnections);
addListenerOnSearchConnTextView();
//Initialize properties
mainListView = (ListView) findViewById( R.id.connectionlist );
mainListView.setOnItemClickListener(this);
// Create and populate a List of planet names.
listNotOnView = new ArrayList<AbstractHolder>();
connlist = new ArrayList<AbstractHolder>(5);
Iterator<AbstractHolder> iter = SocialRssModel.holders.values().iterator();
while(iter.hasNext())
connlist.add(iter.next());
// Create ArrayAdapter using the planet list.
listAdapter = new CustomAdapter(this,
R.layout.connlist, connlist);
mainListView.setAdapter( listAdapter );
}
public void addListenerToFinishButton(){
commitButton = (Button) findViewById(R.id.addConnCommitButton);
commitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void addListenerOnSearchConnTextView(){
searchConnTextView = (TextView) findViewById(R.id.searchEditText);
searchConnTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int listNotOnViewsize = listNotOnView.size();
int connlistsize = connlist.size();
for(int i= 0; i < connlistsize; i++){
if(!connlist.get(i).connNameContains(s.toString())){
listNotOnView.add(connlist.remove(i));
i--;
connlistsize--;
}
}
for(int i=0; i < listNotOnViewsize; i++){
if(listNotOnView.get(i).connNameContains(s.toString())){
connlist.add(listNotOnView.remove(i));
i--;
listNotOnViewsize--;
}
}
((CustomAdapter) listAdapter).updateList(connlist);
listAdapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
AbstractHolder temp = (AbstractHolder)mainListView.getItemAtPosition(arg2);
Intent i = new Intent(this, CategoryContentViewerController.class);
Bundle b = new Bundle();
b.putInt("AbstractHolderKey", temp.getId());
i.putExtras(b);
startActivity(i);
finish();
}
private class CustomAdapter extends ArrayAdapter<AbstractHolder> {
private ArrayList<AbstractHolder> connectionList;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<AbstractHolder> connList) {
super(context, textViewResourceId, connList);
this.connectionList = new ArrayList<AbstractHolder>();
this.connectionList.addAll(connList);
}
public void updateList(ArrayList<AbstractHolder> connList){
connectionList.clear();
connectionList.addAll(connList);
}
private class ViewHolder {
TextView name;
TextView acctype;
CheckBox sel;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)(((Activity)this.getContext()).getSystemService(Context.LAYOUT_INFLATER_SERVICE));
convertView = vi.inflate(R.layout.connlist, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.connname);
holder.acctype = (TextView) convertView.findViewById(R.id.conntype);
holder.sel = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
AbstractHolder conn = connectionList.get(position);
holder.name.setText(conn.getName());
holder.acctype.setText(conn.getConntype());
holder.sel.setChecked(conn.isSelected());
holder.sel.setTag(conn);
return convertView;
}
}
}
It is related to checkbox item in connections.xml which is the list row item. If I remove checkbox, related listeners responses. I think, it may be thought there is no need a setItemOnClickListener(..) method since each row has a checkbox. Or it is a bug.
i am trying to display image using GridView. This is the first time i using GridView, so i using the example from here and implement it to mine (i have tried the example that contained there, and it's works).
But, i have checked it many time, there's no error comes from LogCat, no Force Closed, the image didn't show. i have no idea where's the wrong part.
Here's my code:
choosepic.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bg_inner">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/book_inner"
android:layout_marginTop="50dp"
/>
<ImageButton
android:id="#+id/homeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/home_btn"
android:background="#null"
/>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/bg_arrow_btn"
android:layout_alignParentRight="true"
/>
<ImageButton
android:id="#+id/nextBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/right_arrow"
android:background="#null"
android:layout_alignParentRight="true"
android:layout_marginTop="5dp"
android:layout_marginRight="7dp"
android:layout_marginLeft="7dp"
/>
<ImageButton
android:id="#+id/prevBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/left_arrow"
android:background="#null"
android:layout_toLeftOf="#+id/nextBtn"
android:layout_marginTop="5dp"
/>
<GridView
android:id="#+id/gridView1"
android:numColumns="3"
android:gravity="center"
android:columnWidth="30dp"
android:stretchMode="columnWidth"
android:layout_width="300dp"
android:layout_height="200dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="70dp"
>
</GridView>
</RelativeLayout>
animalbutton.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:visibility="gone">
</TextView>
ImageAdapter.java
public class ImageAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
public ImageAdapter(Activity activity,ArrayList<String> listName, ArrayList<Integer> listImage) {
super();
this.listNm = listName;
this.listAnim = listImage;
this.activity = activity;
}
public static class ViewHolder
{
public ImageView imgViewAnim;
public TextView txtViewAnim;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.animalbutton, null);
view.txtViewAnim = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewAnim = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewAnim.setText(listNm.get(position));
view.imgViewAnim.setImageResource(listAnim.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listNm.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
choosepic.java
public class choosepic extends Activity {
/** Called when the activity is first created. */
ImageAdapter mAdapter;
GridView gridView;
static final String[] animal = new String[] {
"cat", "cow","croc", "duck", "elephant", "giraffe", "lion", "moose", "mouse"};
private ArrayList<String> listNm;
private ArrayList<Integer> listAnim;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choosepic);
gridView = (GridView) findViewById(R.id.gridView1);
prepare_list1();
mAdapter = new ImageAdapter(this,listNm, listAnim);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Toast.makeText(getApplicationContext(), mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepare_list1(){
listNm = new ArrayList<String>();
listAnim = new ArrayList<Integer>();
for (int i = 0; i < animal.length; i++) {
listNm.add(animal[i]);
listAnim.add(getResources().getIdentifier("anim_"+animal[i], "drawable", getPackageName()));
}
}
}
i need some help. i appreciate any help. thank you in advance!
i think the problem is in your getCount() that returns 0 elements
instead of that make it like this
#Override
public int getCount() {
// TODO Auto-generated method stub
return listNm.size();
}