This may not be the correct approach, if there is a better way pleas tell me.
I've created a class of Custom Adapter & in my getView method I inflate the view I want to use
public View getView(int position, View convertView, ViewGroup parent)
{
View v = mInflater.inflate(R.layout.wherelayout, null);
if (convertView != null)
{
v = convertView;
}
HashMap<String, Object> whereHash = (HashMap<String, Object>) this.getItem(position);
if (whereHash != null)
{
TextView whereId = (TextView) v.findViewById(R.id.tvWhere);
TextView whereDetails = (TextView) v.findViewById(R.id.tvWhereDetails);
ImageButton ibDelWhere = (ImageButton) v.findViewById(R.id.ibDelWhere);
whereId.setText((CharSequence) whereHash.get("where"));
whereDetails.setText((CharSequence) whereHash.get("details"));
if (ibDelWhere != null)
{
ibDelWhere.setId(position);
ibDelWhere.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//do stuff when clicked
}
}
);
}
}
return v;
}
The view consists of 2 TextView aligned to the left & an ImageButton aligned to the right, I want to be able to delete the item from the ListView when the button is clicked. the layout is like this -
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal" android:clickable="true">
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="25sp" android:id="#+id/tvWhere" android:textColor="#00FF00" android:text="TextView" android:gravity="top|left" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/tvWhereDetails" android:textColor="#0000FF" android:text="TextView" android:textSize="18sp" android:layout_below="#+id/tvWhere" android:gravity="bottom|left" android:layout_alignParentLeft="true"></TextView>
<ImageButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="#drawable/eraser" android:id="#+id/ibDelWhere" android:layout_alignParentRight="true" android:layout_alignParentTop="true"></ImageButton>
</RelativeLayout>
The problem is that when the ImageButton is in the layout, I can click it & the onClick() fires as expected, but I can't click the actual list item itself, i.e. click on the TextView items to fire the ListView.onItemClick that was assigned to it already. If I remove the ImageButton from the layout, then the ListView.onItemClick event fires when I click the item. Is there any way I can enable clicking both the ListView item & the button within the layout ?
Thanks guys & gals.
You have to set the imagebutton as non focusable and non focusableInTouchMode (clickable is ok).
Please note, as opposed as other views, you can't do that in xml because the android:focusable gets overwritten in ImageButton's constructor.
To be more precise, that's one of the few differences between ImageView and ImageButton. See for yourself, this is the complete source of ImageButton.
#RemoteView
public class ImageButton extends ImageView {
public ImageButton(Context context) {
this(context, null);
}
public ImageButton(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.imageButtonStyle);
}
public ImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
}
#Override
protected boolean onSetAlpha(int alpha) {
return false;
}
}
To solve, just call setFocusable(false) from java. Or use an ImageView :)
myImageButton.setFocusable(false);
Hope it helps.
You can make both clickable, but it's not really supported and Romain Guy will yell at you. Also, you won't be able to focus/press the button with the trackball. With that said, you can add the following properties to the button, which should make both clickable:
android:focusable="false"
android:focusableInTouchMode="false"
Just make sure you can live with the consequences.
Try to set
android:clickable="false" on the relative Layout.
I had the same problem with a LinearLayout inside another Linearlayout.
The outer LinearLayout was clickable=true, result:
The ListView.OnItemClickListener does not fire.
After setting it to clickable=false it works.
i.e. click on the TextView items to fire the ListView.onItemClick that was assigned to it already.
What happens when you click on the TextView while the ImageButton is there? Does it register a click on the button? or do nothing at all?
How much space in the row does the ImageButton take up? It could be that it is large enough that you can't click in the row outside of it.
I had this same problem. My solution was to set the onClick method for the view inside the adapter instead of using onItemClick.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = context.getLayoutInflater();
v = inflater.inflate(R.layout.list_item, parent, false);
}
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//This should replace the onListItemClick method
}
});
v.findViewById(R.id.someinnerview).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Write one of these for each of your inner views
}
});
return v;
}
Hope that helps! Depending on the rest of your program, this might force you into handing more data to the adapter (which I had to do) but it works.
here is example of the custom adapter in list view.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<ImageView
android:layout_width="50dip"
android:layout_height="50dip"
android:id="#+id/imgViewLogo"
android:src="#drawable/icon"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:scaleType="center">
</ImageView>
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewTitle"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_marginLeft="2dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewDescription"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_below="#+id/txtViewTitle"
android:layout_marginLeft="2dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewMobile"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_below="#+id/txtViewDescription"
android:layout_marginLeft="2dip">
</TextView>
and make java file On The BaseAdapter
public class ListViewCustomAdapter extends BaseAdapter {
Context context;
String[] mobile;
String[] month;
String[] number;
public LayoutInflater inflater;
public ListViewCustomAdapter(Context context,String[] month, String[] number, String[] mobile) {
// TODO Auto-generated constructor stub
super();
this.context = context;
this.month=month;
this.number=number;
this.mobile=mobile;
Log.i("88888888888888888","*******333********");
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//ADC71C 95AA1F
public int getCount() {
// TODO Auto-generated method stub
return month.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
ImageView imgViewLogo;
TextView txtViewDescription;
TextView txtViewMobile;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
Log.i("88888888888888888","*******444********");
ViewHolder holder;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null)
{
Log.i("88888888888888888","*******555********");
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescription);
holder.txtViewMobile = (TextView) convertView.findViewById(R.id.txtViewMobile);
convertView.setTag(holder);
}
else
{
Log.i("88888888888888888","*******666********");
holder = (ViewHolder) convertView.getTag();
}
Log.i("888888888888","Display the value of the textbox like(9856321584)other wise (TextView)");
holder.txtViewTitle.setText(month[position]);
holder.txtViewDescription.setText(number[position]);
holder.txtViewMobile.setText(mobile[position]);
return convertView;
}
}
Related
My listview has three textview and one checkbox in horizontal order.
My listview xml code
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="TEXT"
android:id="#+id/textView1"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="TEXT"
android:id="#+id/textView2"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="10" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="TEXT"
android:id="#+id/textView3"
android:textSize="20sp"
android:gravity="center"
android:layout_weight="5" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/checkBox1"
android:focusable="false"
android:clickable="false"
android:layout_gravity="right"
android:layout_marginRight="10dp"/>
and MainActivity.java code
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView,
View view, int position, long id) {
Object vo = (Object)adapterView.getAdapter().getItem(position);
Log.d(TAG, String.valueOf(vo));
}
});
The log output for String.valueOf(vo) is
sn.studyroom.ListViewItem#f085546
How can I get each of the three Textview values?
If you catch the clicked object right, you must convert it to TextView, and then get your TextView's text like this:
String vo = ((TextView)adapterView.getAdapter().getItem(position)).getText().toString();
Log.d(TAG, vo);
OR
Go your adapter class and create an interface to get clicked item's values.
You can use adapter for accessing your text fields and check box. Pass your list to a adapter like this:
CustomListAdapter adapter = new CustomListAdapter (context, yourList);
yourListView.setAdapter(adapter);
Create an adapter like this.
public class CustomListAdapter extends BaseAdapter {
Context context;
List<ListObject> yourList;
public CustomListAdapter (Context context, List<ListObject> yourList) {
this.context = context;
this.yourList= yourList;
}
public void refreshAdapter(List<ListObject> yourList){
this.yourList= yourList;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView textView1, textView2, textView3;
CheckBox checkBox1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return yourList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return yourList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.your_adapter_layout, null);
holder = new ViewHolder();
holder.textView1= convertView.findViewById(R.id.textView1);
holder.textView2= convertView.findViewById(R.id.textView2);
holder.textView3= convertView.findViewById(R.id.textView3);
holder.checkBox1= convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//TODO: you can do whatever you want to do here
return convertView;
}
}
If you want to retrive list data then i want to know about to set data. Are you set model and add in adapter or taking static string arraylist? so let me know then i will suggest better way to do that.
I'm using a Gridview to show a list of skills. The code runs fine, even populates exact number of items according to my array. However, the TextView that should display the item names is blank.
This is the code for my gridview adapter
SkillsAdapter.java
public class SkillsAdapter extends BaseAdapter {
private Context context;
private final String[] skillValues;
public SkillsAdapter(Context context, String[] skillValues) {
this.context = context;
this.skillValues = skillValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
textView.setText(skillValues[position]);
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return skillValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
This is the code for my layout file skills_single_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:background="#drawable/rounded_corners">
<TextView
android:id="#+id/single_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center"/>
</RelativeLayout>
The array is not null. The error occurs somewhere around here
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
textView.setText(skillValues[position]);
Change your layout Item XML with this your I used your Adapter class its work fine at my side
it may help you
<?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:background="#FFFFFF"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="#+id/single_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="8dp"
android:textColor="#000000" />
</RelativeLayout>
Set test in your text view out of if condition like:
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
// set value into textview
textView = (TextView) gridView.findViewById(R.id.single_label);
} else {
gridView = (View) convertView;
}
textView.setText(skillValues[position]);
Move following line out of if-else blocks
textView.setText(skillValues[position]);
Like
if (convertView == null) {
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.skills_single_item, null);
textView = (TextView) gridView.findViewById(R.id.single_label);
} else {
gridView = (View) convertView;
}
// set value into textview
textView.setText(skillValues[position]);
I recommend you to read android ViewHolder pattern.
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
I have a list view every item in list contains textviews and button what I want is when I click on the button of any item in list I want to printout the position of button if i clicked the button in first line i want to print out 0 and go on but it doesn't work
this is my method to display view
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[] {
PhonesDbAdapter.KEY_NAME,
PhonesDbAdapter.KEY_CONTINENT,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.continent,
R.id.name
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.phone_layout,
cursor,
columns,
to,
0);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
public void print(View v)
{
}
and here how my item look like
<?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="wrap_content"
android:orientation="vertical"
android:padding="6dip"
android:background="#f0f0f0" >
<TextView
android:id="#+id/continent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#275a0d"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="TextView"
android:textColor="#000"/>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/ic_launcher"/>
<Button
android:id="#+id/call"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button1"
android:background="#drawable/ic_launcher"
android:onClick="print"/>
</RelativeLayout>
and this the layout that contain the listview
<?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:background="#f0f0f0">
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10">
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
i spent alot of time with this problem and i hope that u can help me and im really sorry for my bad english
Are you implementing the method getView() on your adapter?
That's where you want to add the OnClickListener to your Button
Once you do that you can set the position as the tag of the Button and retrieve it on the onClick method.
Something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.your_item_layout, parent, false);
Button myButton = (Button) row.findViewById(R.id. call);
myButton.setOnClickListener(new OnClickListener {
#Override
public void onClick(View view) {
int position = (int)view.getTag();
//Do whatever you want with the position here
}
});
myButton.setTag(position);
return row;
}
From last 3 three years I am not working on android so I am not sure my suggestion is correct or not. You need to test it for you purpose.
In your above case you cannot use onItemClickListner because it can only be used when you are tracking your complete list row. What I think is you can create a custom adapter and override its getView method. In getView method you will have your position and you can set button click listner for you button in getview. So In this way you can get your button position.
You try it once if you need some code then I can try to write it for you...
THIS IS HOW YOU CAN CREATE CUSTOM ADAPTER.
public class my_custom_adapter extends ArrayAdapter<String> {
private Context context = null;
ArrayList<String> elements = null;
public my_custom_adapter(Context context, int type, ArrayList<String> elements)
{
super(context, type, elements);
this.elements = elements;
this.context = context;
}
//THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
static class ViewHolder
{
public TextView tv;
public Button cb;
}
#Override
public View getView (final int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
ViewHolder holder = null;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
// HERE I AM INFLATING LISTVIEW LAYOUT.
rowView = inflater.inflate(R.layout.inflated_layout, null, false);
holder = new ViewHolder();
holder.cb = (Button) rowView.findViewById(R.id.checkBox1);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
if (holder != null) {
holder.cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// IF YOUR BUTTON TAG HERE AND YOU CAN HAVE POSITION USING "position" PARAMETER
}
});
}
return rowView;
}
}
I am trying to show a list that when I pressed it in that position I would like to show an image that is gone and to change the typeface of that row. So first I have a xml file with a simple list and then another xml for each row, this one:
<ImageView
android:id="#+id/icono"
android:layout_gravity="center"
android:layout_marginRight="5dip"/>
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:text="TextView" />
<ImageView
android:id="#+id/image_tick_ingred"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="true"
android:layout_alignParentTop="false"
android:layout_alignRight="#id/textView1"
android:layout_centerVertical="true"
android:src="#android:drawable/presence_online" />
</RelativeLayout>
So that is the code to each row, contains an image on the left then a text and finally another image on the right of the row. And the java code:
public class TabIngred extends ListActivity {
ImageView img;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rellenas_ingr); //the list xml layout
Bundle extras = getIntent().getExtras(); //get data
if (extras != null) {
String ingredientesLista[] = extras.getStringArray("ingredientesLista");
int[] ingredientesImagen=extras.getIntArray("ingredientesImagen");
setListAdapter (new IngredienteAdapter(this, R.layout.rellenas_ingr_fila, ingredientesLista, ingredientesImagen));
getListView().setChoiceMode(2);
}
}
private class IngredienteAdapter extends ArrayAdapter<String>{
private String listaIngred[];
private int[] listaImagenes;
public IngredienteAdapter(Context context, int textViewResourceId, String ingredientesLista[], int[] ingredientesImagen) {
super(context, textViewResourceId, ingredientesLista);
this.listaIngred = ingredientesLista;
this.listaImagenes=ingredientesImagen;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// XML de la vista de la fila
v = vi.inflate(R.layout.rellenas_ingr_fila, null); //the row for the listview
}
String ingred = listaIngred[position];
int imagen=listaImagenes[position];
int tickImagen = R.drawable.tick_ingred;//set the image to a tick
if (ingred != null) {
TextView ttitulo = (TextView) v.findViewById(R.id.textView1);
if (ttitulo != null) {
ttitulo.setText(ingred);
}
ImageView timagen = (ImageView) v.findViewById(R.id.icono);
if (timagen != null) {
timagen.setImageResource(imagen);
}
ImageView ttick = (ImageView) v.findViewById(R.id.image_tick_ingred);
if (ttick != null) {
ttick.setImageResource(tickImagen);
ttick.setVisibility(View.GONE);
}
}
return v;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
img=(ImageView)v.findViewById(R.id.image_tick_ingred);
TextView t= (TextView)v.findViewById(R.id.textView1);
if(img.getVisibility()==View.GONE){
t.setTypeface(null, Typeface.BOLD);
img.setVisibility(View.VISIBLE);
}else {
t.setTypeface(null, Typeface.NORMAL);
img.setVisibility(View.GONE);
}
}
}
So, I define the getview(), I put the image on gone (thats works), but then the OnlistItemClick() doesn´t work. First when I selected an Item the image isn´t visible and apart for that indefferently the position I pressed the first row is which change the typeface, not the item what I pressed.
Thanks :)
in you onListItemClick you need to use the View
for example:
img=(ImageView)findViewById(R.id.image_tick_ingred);
TextView t= (TextView)findViewById(R.id.textView1);
should be
img=(ImageView)v.findViewById(R.id.image_tick_ingred);
TextView t= (TextView)v.findViewById(R.id.textView1);
notice the v that is the view of the row clicked
The problem was that I define getListView().setChoiceMode(2); and that was because it doesn´t work, I delete the line and works perfect!!
Thanks after all!