GridView.setOnItemClickListener is not triggering - android

I am trying to add a feature where, whenever the user clicks on an editText to start typing in the last empty gridview item, a new empty gridview item will be added. The problem is that the listener doesn't get called when the user starts typing. I know there are some questions here about similar issues, but my gridView has an editText in it which is what I think the problem is.
Here is the listener I have:
roleLayout.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println(roleArrayList.get(position).getRole() + "******");
if(roleArrayList.get(position).getRole().equals("")) {
if (roleArrayList.size() == 1 ) {
roleArrayList.add(new NewRoleElement());
} else {
if (!roleArrayList.get(roleArrayList.size() - 1).getRole().equals("")) {
roleArrayList.add(new NewRoleElement());
}
}
}
}
});
And here is the xml code for my GridView:
<GridView
android:id="#+id/roleList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:numColumns="1"
android:stretchMode="columnWidth" />
Here is my xml code for the actual item:
<?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="48dp"
android:layout_rowWeight="1"
android:background="#drawable/my_layout_bg"
android:orientation="horizontal">
<EditText
android:id="#+id/roleText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10"
android:hint="Enter a new role"
android:inputType="textPersonName" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3"
android:text="Repeat?" />
</LinearLayout>
My adapter code is here:
public class RoleAdapter extends BaseAdapter{
Context c;
public RoleAdapter(Context context) {
this.c = context;
}
#Override
public int getCount() {
return roleArrayList.size();
}
#Override
public Object getItem(int position) {
return roleArrayList.get(position);
}
#Override
public long getItemId(int position) {
return roleArrayList.indexOf(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.role_template, null);
}
roleArrayList.get(position).setRoleInput((EditText) convertView.findViewById(R.id.roleText));
roleArrayList.get(position).setRepeatCheckBox((CheckBox) convertView.findViewById(R.id.checkBox));
return convertView;
}
}

The main problem is that EditText and CheckBox capture the focus
Try this in your code.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_rowWeight="1"
android:descendantFocusability="blocksDescendants"
android:background="#drawable/my_layout_bg"
android:orientation="horizontal">
......
</LinearLayout>
Add android:descendantFocusability="blocksDescendants" in the root xml code .
Another way
Also you can set android:focusable="false" in the EditText and set android:clickable="false" in the CheckBox.

Related

Android Custom Spinner unable to select an option and show it

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);

Android ListView requires two fingers to scroll

I have a rather simple layout that I am intending on using for basic chat in a fragment, but scrolling through the ListView requires me to place one finger on the screen on an item in the ListView and then scroll up or down with another finger. I was under the impression that a ListView should only require a single finger/touch to be able to scroll. Is there something I am overlooking in my layout, adapter or even potentially the code I am using to populate the adapter with?
Chat Layout XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<ListView
android:id="#+id/msgListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/form"
android:divider="#null"
android:dividerHeight="0dp"
android:scrollbarSize="3dp"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:scrollingCache="true"
android:smoothScrollbar="true"
android:paddingBottom="10dp" />
<LinearLayout
android:id="#+id/form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#color/primary"
android:orientation="horizontal"
android:paddingBottom="2dp" >
<EditText
android:id="#+id/messageEditText"
android:layout_width="252dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/button1"
android:layout_toLeftOf="#+id/sendMessageButton"
android:layout_weight="0.72"
android:ems="10"
android:maxHeight="80dp" />
<ImageButton
android:id="#+id/sendMessageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/chat_send_button" />
</LinearLayout>
</RelativeLayout>
ListView Adapter
public class ChatMessageAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
ArrayList<ChatMessage> chatMessageList;
public ChatMessageAdapter(Activity activity, ArrayList<ChatMessage> list) {
chatMessageList = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageList.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) {
ChatMessage message = chatMessageList.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_bubble, null);
TextView msg = (TextView) vi.findViewById(R.id.message_text);
msg.setText(message.body);
TextView dateTime = (TextView) vi.findViewById(R.id.msgDateTime);
dateTime.setText(message.dateTime);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
// if message is mine then align to right
if (message.isMine) {
layout.setBackgroundResource(R.drawable.bubble2);
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setBackgroundResource(R.drawable.bubble1);
parent_layout.setGravity(Gravity.LEFT);
}
msg.setTextColor(Color.BLACK);
return vi;
}
public void add(ChatMessage object) {
chatMessageList.add(object);
}
}
I had the same problem!
If you're using the navigation drawer, in the app_bar_main.xml change the CoordinatorLayout for the NestedScrollView
and then in your fragment in the scrollView set android:nestedScrollingEnabled="true"

OnItemClickListener not working but OnItemLongClickListener is working on GridView

I am having a problem with a clickListener on my gridview. The LongClickListener works without issue. But I cannot seem to get any response from the click Listener.
My code is below.
Im confused as to why the long click works but not the normal click,
Any pointers would be appreciated
Thanks
final GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setNumColumns(numOfColumns);
gridView.getLayoutParams().width = (CELL_WIDTH * numOfColumns);
gridView.getLayoutParams().height = (CELL_WIDTH * numOfRows);
....
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Log.d("ABCD", "Position Single Click is " + position);
// Ideally in here I want to put to open a soft keyboard for the user to enter a value
// InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(gridView, InputMethodManager.SHOW_IMPLICIT);
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ABCD", "Position Long Click is " + position);
return true;
}
});
grid_view is
<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:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_grid_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"/> <<--- I WANT THIS TO GET THE CLICK
<View
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
</LinearLayout>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listId"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp" />
</LinearLayout>
GridCell in the grid view is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="0dp" android:layout_margin="0dp"
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
>
<TextView
android:id="#+id/grid_item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="1dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textSize="10px"
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
>
</TextView>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/celllabel"
android:background="#android:color/transparent"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:layout_margin="0dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:cursorVisible="false">
</EditText>
</RelativeLayout>
The adapter class has a getView and is as below
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
MyObject obj = myObjects.get(position);
if (convertView == null) {
gridView = inflater.inflate(R.layout.grid_cell, null);
String textColour = "#000000";
TextView textView = (TextView) gridView.findViewById(R.id.grid_item_label);
textView.setText(Html.fromHtml(String.format("<font color='%s'>%s</font>", textColour, obj.getValue())));
TextView superScriptTv = (TextView) gridView.findViewById(R.id.grid_item_number);
if (obj.getNumber() > 0) {
superScriptTv.setText(Html.fromHtml(String.format("<font>%s</font>", cell.getNumber())));
}
} else {
gridView = convertView;
}
gridView.setBackgroundColor(obj.getBackgroundColour());
return gridView;
}
EDIT
Really banging my head against a wall here now :)
Im updating the code sample so have more data. Ive noticed that in my adapter if I do not set the text on the textview with ID = R.id.grid_item_number then it works. As soon as I set text on it then I lose the click listener.
The linked question/answer doesnt help from what I can see. Can anyone help with my stupidity?
EDIT
Adapter code has been added.
Thanks in advance.
The problem is with the EditText inside the row_cell. When you click on the item, it takes focus and prevents the whole item to be clickable again. As you noticed, only long click works.
Here you have a similar problem.
To resolve that issue I would move your OnItemClickListeners from the Activity / Fragment to your GridViewAdapter, so instead of:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Log.d("ABCD", "Position Single Click is " + position);
// Ideally in here I want to put to open a soft keyboard for the user to enter a value
// InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(gridView, InputMethodManager.SHOW_IMPLICIT);
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("ABCD", "Position Long Click is " + position);
return true;
}
});
I would do something like that:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridViewItem;
if (convertView == null) {
gridViewItem = new View(mContext);
gridViewItem = layoutInflater.inflate(R.layout.grid_cell, null);
TextView textView = (TextView)gridViewItem.findViewById(R.id.grid_item_number);
textView.setText(mValues[position]);
EditText editText = (EditText)gridViewItem.findViewById(R.id.grid_item_label);
} else {
gridViewItem = (View) convertView;
}
gridViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("GRID", "onClick: " );
}
});
gridViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.e("GRID", "onLongClick: " );
return true;
}
});
return gridViewItem;
}
It will prevent this strange behaviour you are struggling right now.
For the sake of that example please find my code below:
MainActivity layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="io.github.mmbs.gridviewcheck.MainActivity"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<GridView
android:id="#+id/gridView"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
</GridView>
</android.support.constraint.ConstraintLayout>
Grid cell layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="8dp">
<TextView
android:id="#+id/grid_item_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="0dp"
android:paddingLeft="1dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:textSize="20sp"
android:text="TEXTVIEW">
</TextView>
<EditText
android:id="#+id/grid_item_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:background="#android:color/transparent"
android:cursorVisible="false"
android:layout_below="#id/grid_item_number"
android:text="EDITTEXT">
</EditText>
</RelativeLayout>
Please take into consideration, that I removed all layouts attributes responsible for focusability.
MyGridAdapter:
public class MyGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] mValues;
public MyGridViewAdapter(String[] values, Context context) {
mValues = values;
mContext = context;
}
#Override
public int getCount() {
return mValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridViewItem;
if (convertView == null) {
gridViewItem = new View(mContext);
gridViewItem = layoutInflater.inflate(R.layout.grid_cell, null);
TextView textView = (TextView)gridViewItem.findViewById(R.id.grid_item_number);
textView.setText(mValues[position]);
EditText editText = (EditText)gridViewItem.findViewById(R.id.grid_item_label);
} else {
gridViewItem = (View) convertView;
}
gridViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("GRID", "onClick: " );
}
});
gridViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.e("GRID", "onLongClick: " );
return true;
}
});
return gridViewItem;
}
}
If you like, I can also share this code on github, so you will have a fully operational example.
The second option is to leave your implementation as it is and do hacks when the EditText is focusable and enabled. Here you have related topics:
Android: Force EditText to remove focus?
ListView items focus behaviour
Focusable EditText inside ListView
Android: Force EditText to remove focus?
What is more, please take into account that answer:
Do not use clickable objects in the grid. In that case Android cannot handle the click event of GridView.
Instead, use something to show a similar user interface view. Then handle that object's click actions.
Don't: put Button in the GridView to perform some click actions.
Do: put an ImageView instead of ImageButton and handle ImageView's click events.
Edit: Please find a link to the project on my Github.
use gridView.setOnItemClickListener(.....) and to your root view add below line
android:descendantFocusability="blocksDescendants"
The ViewGroup will block its descendants from receiving focus.
Try to add
android:focusable="false"
android:focusableInTouchMode="false"
in your GridCell -->TextView
Try using recycler view if you are comfortable with it.
It doesn't gives any such problem in addition to this it has its own advantages.
Follow the link for complete explanation.
If you have any focus-able view in you your row layout, then the onItemClickListener will not be called. For this problem you need to customize your getView code and set onClickListener() on convertView and pass the callback to activity using the Interface. I have updated the code of your Adapter as below. Now you need to implement the GridViewItemClickListener on your activity and pass the instance while creating the Adapter instance.
public class MyGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] mValues;
private GridViewItemClickListener mListener;
public MyGridViewAdapter(String[] values, Context context,GridViewItemClickListener listener ) {
mValues = values;
mContext = context;
mListener = listener;
}
#Override
public int getCount() {
return mValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridViewItem;
if (convertView == null) {
gridViewItem = new View(mContext);
gridViewItem = layoutInflater.inflate(R.layout.grid_cell, null);
TextView textView = (TextView)gridViewItem.findViewById(R.id.grid_item_number);
textView.setText(mValues[position]);
EditText editText = (EditText)gridViewItem.findViewById(R.id.grid_item_label);
} else {
gridViewItem = (View) convertView;
}
gridViewItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Log.e("GRID", "onLongClick: " );
return true;
}
});
//Add an OnclickListener here
gridViewItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mListener != null){
mListener.onGridItemClick(v, position);
}
}
});
return gridViewItem;
}
public interface GridViewItemClickListener{
void onGridItemClick(View v, int index);
}
}
You can user click listeners inside the adapter it will work ,it should work like this
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
MyObject obj = myObjects.get(position);
if (convertView == null) {
gridView = inflater.inflate(R.layout.grid_cell, null);
String textColour = "#000000";
TextView textView = (TextView) gridView.findViewById(R.id.grid_item_label);
textView.setText(Html.fromHtml(String.format("<font color='%s'>%s</font>", textColour, obj.getValue())));
TextView superScriptTv = (TextView) gridView.findViewById(R.id.grid_item_number);
superScriptTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// here you can use every item of grid acc to position
}
});
if (obj.getNumber() > 0) {
superScriptTv.setText(Html.fromHtml(String.format("<font>%s</font>", cell.getNumber())));
}
} else {
gridView = convertView;
}
gridView.setBackgroundColor(obj.getBackgroundColour());
return gridView;
}
how can the click listener work if you set the root element in GridCell.java as non-clickable ?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:padding="0dp" android:layout_margin="0dp"
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
Remove those lines from each of your components in the GridCell.java
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
I don't think this is required for GridView, but sometimes for RecyclerView it is required to have android:clickable="true" on the root componenent of GridCell.java

GridView breaks while scrolling

I am working on a custom launcher application. For this reason I created a custom GridView that displays all installed applications.
The problem is that when I scroll through the apps, the gridview has a weird behavior. Sometimes it will break the horizontal alignment because of a multiline application name. Sometimes the scrolling bounds go crazy and you end up scrolling outside the gridview.
Here is a video of the problems I describe above.
I am using the following code.
public class CustomGridView extends BaseAdapter{
private Context mContext;
private List<Application> app;
public CustomGridView(Context c, List<Application> app) {
super();
mContext = c;
this.app = app;
}
#Override
public int getCount() {
return app.size();
}
#Override
public Object getItem(int position) {
return app.get(position).appPkg;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_item, null);
view = new ViewHolder();
view.appName = (TextView) convertView.findViewById(R.id.grid_text);
view.appIcon = (ImageView) convertView.findViewById(R.id.grid_image);
convertView.setTag(view);
} else {
view = (ViewHolder) convertView.getTag();
}
view.appName.setText(app.get(position).appName);
view.appIcon.setImageDrawable(app.get(position).appIcon);
return convertView;
}
static class ViewHolder
{
ImageView appIcon;
TextView appName;
}
}
For the grid_item I use the following.
<?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:padding="10dp"
android:layout_marginBottom="10dp"
android:gravity="fill_horizontal|center_horizontal">
<ImageView
android:layout_height="62dp"
android:id="#+id/grid_image"
android:layout_width="62dp"
android:layout_gravity="center_horizontal"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/grid_text"
android:layout_marginTop="2dp"
android:textSize="12sp"
android:ellipsize="marquee"
android:gravity="center|center_horizontal" android:textAlignment="center"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
And here is the activity layout
<GridView
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnWidth="80dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" android:layout_alignParentTop="true">
</GridView>
The problem with the height of TextView. So, make TextView single line like:
android:singleLine="true"
or, If u want 2 or 3 lines for some of the items, then make all the items have 2 or 3 lines like:
android:minLines="2"

Get Item from a ListView

My app is displaying 3 String with 3 Text-view in a list-view.
My Problem is that I create on layout for my list-view and i am not able to get the item from the first text view in the onListItemClick method.
How can I achieve achievement this?
Layout of the ListView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/outputlayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#color/ligthgrey">
<TextView
android:id="#+id/txOutputDeparture"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Abfahrt "
android:textColor="#color/black"
android:layout_alignParentLeft="true"
android:maxLength="#android:integer/config_shortAnimTime"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/txOutputDuration"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txOutputDeparture"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Dauer"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/txOutputTransition"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/txOutputDuration"
android:text="Umstieg"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="5dp" />
</RelativeLayout>
Method where i create and fill the listView and its and ListActivity
public void getRoute() {
mdbH = new DatabaseHelperActivity(this);
cursor = mdbH.fetchallRoutes(intent.getStringExtra("StartHaltestelle"),intent.getStringExtra("ZielHaltestelle"), intent.getStringExtra("Zeit"));
ArrayList<DefineRouteActivity> route = new ArrayList<DefineRouteActivity>();
while(cursor.moveToNext()) {
route.add(new DefineRouteActivity(cursor.getString(0),cursor.getString(2),cursor.getString(4)));
}
ArrayAdapter<DefineRouteActivity> adapter = new RouteAdapterActivity(this, route);
setListAdapter(adapter);
}
AdapterActivity:
Activity context;
ArrayList<DefineRouteActivity> arraylist;
public RouteAdapterActivity(Activity context, ArrayList list) {
super(context,R.layout.outputlayout,list);
this.context = context;
arraylist = list;
}
#Override
public int getCount() {
return arraylist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View contentview, ViewGroup viewGroup) {
DefineRouteActivity routeItems = arraylist.get(position);
LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.outputlayout,null);
TextView tvDeparture = (TextView)view.findViewById(R.id.txOutputDeparture);
tvDeparture.setText(routeItems.getAbfahrtszeit());
TextView tvDuration = (TextView)view.findViewById(R.id.txOutputDuration);
tvDuration.setText(routeItems.getDauer());
TextView tvTransition = (TextView)view.findViewById(R.id.txOutputTransition);
tvTransition.setText(routeItems.getUmstieg());
return view;
}
Here is my onClick Method:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
((View)v).
Intent detail = new Intent(getApplicationContext(),DetailOutputActivity.class);
detail.putExtra("StartStop",l.getItemAtPosition(0).toString());
detail.putExtra("EndStop","ich");
detail.putExtra("Time","du");
detail.putExtra("Route","er");
startActivity(detail);
}
Here is my Layout containing the listView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
You need another xml containing the listView.
For example: sample.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
In your mainActivity.java:
setContentView(R.layout.sample.xml);
lv = (ListView)findViewById(R.id.lv1);
lv.setOnItemClickListener(this);
Your listActivity must implement OnItemClickListener.
Then implements onItemClick method. Example:
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
// TODO Auto-generated method stub
int id_object = ((object)a.getAdapter().getItem(position)).getIdInstalacion();
Intent i = new Intent(this, Other.class);
i.putExtra("id_", id_object);
startActivity(i);
}

Categories

Resources