I am working on an Android application and I am trying to make the item click on a listView with custom adapter to work but am not being able to. I have my OnItemClickListener implemented inside the customer adapter.
Would you know what I can be doing wrong? ListView loads with content correctly, only point is that it does not clicks.
This is my listView definition and adapter setting:
public void updateUserAssetBookingsListView(final ArrayList<AssetBooking> userAssetBookings) {
System.out.println("Bookings updated, new total is: " + userAssetBookings.size());
BookingAdapter bookingAdapter = new BookingAdapter(getContext(), 0, userAssetBookings);
userAssetBookingsListView.setAdapter(bookingAdapter);
userAssetBookingsListView.setOnItemClickListener(bookingAdapter);
}
This is my custom adapter:
package it.bitrack.adapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.Toast;
import org.w3c.dom.Text;
import it.bitrack.fabio.bitrack.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import it.bitrack.support.Epoch;
import it.bitrack.support.AssetBooking;
/**
* Created by fabio on 25/04/2017.
*/
public class BookingAdapter extends ArrayAdapter<AssetBooking> implements AdapterView.OnItemClickListener {
ArrayList<AssetBooking> userAssetBookings;
Epoch epoch = new Epoch();
public BookingAdapter(#NonNull Context context, #LayoutRes int resource, ArrayList<AssetBooking> userAssetBookings) {
super(context, resource, userAssetBookings);
this.userAssetBookings = userAssetBookings;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
AssetBooking ab = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.booking_listview_layout, parent, false);
}
// Lookup view for data population
TextView assetTextView = (TextView) convertView.findViewById(R.id.assetTextView);
TextView fromTextView = (TextView) convertView.findViewById(R.id.fromTextView);
TextView toTextView = (TextView) convertView.findViewById(R.id.toTextView);
TextView durationTextView = (TextView) convertView.findViewById(R.id.durationTextView);
ImageButton cancelImageButton = (ImageButton) convertView.findViewById(R.id.cancelImageButton);
cancelImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "You tried to delete this row " + position, Toast.LENGTH_SHORT).show();
}
});
// Populate the data into the template view using the data object
// AssetBooking ab = userAssetBookings.get(position);
long from = ab.getFromDatetime() / 1000;
long to = ab.getToDatetime() / 1000;
long delta = (to - from);
long deltaDays = delta / 86400;
long deltaMinutes = ((delta % 86400) / 60) % 60;
long deltaHours = (delta % 86400) / 3600;
assetTextView.setText(ab.getNetworkAssetCode() + ": " + ab.getAssetDescription());
fromTextView.setText(epoch.getDatetimeFromTimestampNoSeconds(from));
toTextView.setText(epoch.getDatetimeFromTimestampNoSeconds(to));
durationTextView.setText(deltaDays + " day(s) " + deltaHours + " hour(s) " + deltaMinutes + " min(s)");
// Return the completed view to render on screen
return convertView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
// set title
alertDialogBuilder.setTitle("Bookings details");
// set dialog message
alertDialogBuilder
.setMessage("Booker name: " + userAssetBookings.get(position).getUserName() + " " + userAssetBookings.get(position).getUserLastName() +
"\nBooker e-mail address: " + userAssetBookings.get(position).getUserEmail() +
"\nBooking date: " + epoch.getDatetimeFromTimestampNoSeconds(userAssetBookings.get(position).getCreatedOn() / 1000))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
Couple of things in your booking_listview_layout.xml
Add android:descendantFocusability="blocksDescendants" to the root layout.
Also if you add android:clickable="true" in your layout remove it and also add android:focusable="false". ---if the first case not worked.
Second approach
Add a clickListener to the view object inside getView() method..it will call upon entire row.
Code snippet:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.booking_listview_layout, parent, false);
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context).setTitle("touched").show();
}
});
return convertView;
}
Inside the 'getView()' method try putting an OnClickListener on the convertview in the following way:
convertview.setOnClickListener(new OnClickListener(){
...............YOUR CODE HERE.............
})
see if this works and dont implement onitemclicklistener
Related
I have a listview in which i load data with cursor adapter and content provider, the data is loading and scrolling correctly except of background, the view background is not able to save its state....so i had tried my every approach to save the background of view but i failed...any help would be greatly appreciated.
package papuu.items;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import papu.R;
import papu.db.Order;
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View vView = LayoutInflater.from(context).inflate(R.layout.listview_item_row, parent, false);
vView.setTag(new ViewHolder(vView));
// no need to bind data here. you do in later
return vView;// **EDITED:**need to return the view
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View row, Context context, Cursor cursor) {
Order cPerson = new Order(cursor);
//here the row background is not able to save its background state, as i scroll the row background gets shuffled
if (cPerson.status == 3)
row.setBackgroundColor(Color.parseColor("#8FCC85")); //Green Accepted
else if (cPerson.status == 0)
row.setBackgroundColor(Color.parseColor("#B0BEC5")); //gray Picked Up
ViewHolder vh = (ViewHolder) row.getTag();
vh.restaurentName.setText(cPerson.restaurantName);
vh.address.setText(cPerson.customerAddress);
DateFormat df = new SimpleDateFormat("yyyy'-'mm'-'dd'T'hh':'mm':'SS'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date;
int mins = 0;
int hrs = 0;
try {
date = df.parse(cPerson.pickupTime);
hrs = (int) ((date.getTime() / (1000 * 60 * 60)) % 24);
mins = (int) ((date.getTime() / (1000 * 60)) % 60);
} catch (Exception ex) {
ex.printStackTrace();
}
// Log.e(cPerson.status + "",mins+"");
vh.pickupTime.setText(hrs + ":" + mins);
vh.price.setText("Tk. " + cPerson.status);
}
public class ViewHolder {
TextView restaurentName;
TextView address;
TextView pickupTime;
TextView price;
ViewHolder(View row) {
restaurentName = (TextView) row.findViewById(R.id.tv_restaurent_name);
address = (TextView) row.findViewById(R.id.tv_address);
pickupTime = (TextView) row.findViewById(R.id.tv_pickuptime);
price = (TextView) row.findViewById(R.id.tv_price);
}
}
}
I am a new android developer and I need your help. I created a simple listview. User can add some item in listview (type in EditText and click on Button "OK"). When user made onItemClick , the app will strike out text and set background green.
But then , when I add one more item,I see that it applies that strike out and background option from previously item.
Can you advise me what I need to do in this situation? How to improve it?
package com.example.boytsov.foodbasketapp;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Boytsov on 23.07.2015.
*/
public class ProductList extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,TextView.OnEditorActionListener {
EditText myText;
ListView lvMain;
ArrayList<String> catnames;
ArrayAdapter<String> adapter;
Button button;
DataBase db;
final String LOG_TAG = "myLogs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productlist);
db = new DataBase(this);
myText = (EditText)findViewById(R.id.editText);
lvMain = (ListView) findViewById(R.id.lvMain);
button=(Button)findViewById(R.id.button);
catnames= new ArrayList<String>();
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, catnames);
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(this);
lvMain.setOnItemLongClickListener(this);
// Прослушиваем нажатия клавиш
button.setOnClickListener(this);
//слушаем edittext
myText.setOnEditorActionListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button : {
//TextView myText = (TextView) view;
catnames.add(0, myText.getText().toString());
adapter.notifyDataSetChanged();
//myText.setBackgroundColor(Color.TRANSPARENT);
//myText.setPaintFlags(0);
Log.d("Insert: ", "Inserting ..");
db.addProduct(new Product(myText.getText().toString()));
myText.setText("");
Log.d("Reading: ", "Reading all contacts..");
List<Product> products = db.getAllProducts();
for (Product cn : products) {
String log = "Id: "+cn.getID_product()+" ,Name: " + cn.getName_product();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView textview= (TextView) view;
if (textview.getPaintFlags() != 16){
textview.setPaintFlags(16);
textview.setBackgroundColor(Color.parseColor("#77dd77"));
Toast.makeText(this, "Куплено", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
Log.d(LOG_TAG, "itemClick: position = " + i + ", id = "
+ l);
} else {
textview.setPaintFlags(0);
textview.setBackgroundColor(Color.TRANSPARENT);
Toast.makeText(this, "Не куплено", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
catnames.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Удалено", Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "onItemClick: position = " + position + ", id = "
+ id);
return true;
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
Log.d(LOG_TAG, "onItemClick: position = " + actionId + ", id = "
+ event);
handled = true;
}
return handled;
}
}
You apply your changes on the view at position 0.
When you add your item you also add it to position 0, hence the entire list is pushed down by 1 and the new item get the already changed view.
Edited Answer
Sorry, I was short on time, but now I can address it more thoroughly.
One important thing you must understand is that the view which shows your data in the list view DOES NOT NECESSARILY correspond with your data.
If you click on an item in your list and change it's views attributes, it doesn't change the state for the item or object which represents the data, but the view itself.
For example if you click on item at position 0 it will change the view's background at position 0. Then, in your example, you add an item at the top of the list, which puts the newly created object at position 0 (with the already modified view) and pushes THE REST OF THE ALREADY CREATED DATA by one, And you end up with an already changed view at position 0 with new data at position 0.
What you should do is as follows:
1)Make sure your object has a boolean member which states if item is "strike out" or not. like for example mIsStrikeOut.
2)create a custom adapter from any android adapter, like from ArrayAdapter.
3)Override it's getView method, for example:
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
{
view = (LinearLayout) inflater.inflate(R.layout. simple_list_item_1, parent, false);
}
TextView textview = (TextView) view.findViewById(R.id.text1);
if (catnames.get(position).isStrikeOut())
{
textview.setPaintFlags(16);
textview.setBackgroundColor(Color.parseColor("#77dd77"));
Toast.makeText(this, "Куплено", Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "itemClick: position = " + i + ", id = "
+ l);
}
else
{
textview.setPaintFlags(0);
textview.setBackgroundColor(Color.TRANSPARENT);
Toast.makeText(this, "Не куплено", Toast.LENGTH_SHORT).show();
}
return view;
}
Side note:
When you query your data from your DB make sure the order is correct, I would suggest ORDER BY id dec or something like that.
I do not really know if this is the right answer but it is a suggestion :
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button : {
//TextView myText = (TextView) view;
catnames.add(0, myText.getText().toString());
View view = listView.getChildAt(0);
TextView textview= (TextView) view;
textview.setBackgroundColor(Color.TRANSPARENT);
adapter.notifyDataSetChanged();
//myText.setBackgroundColor(Color.TRANSPARENT);
//myText.setPaintFlags(0);
Log.d("Insert: ", "Inserting ..");
db.addProduct(new Product(myText.getText().toString()));
myText.setText("");
Log.d("Reading: ", "Reading all contacts..");
List<Product> products = db.getAllProducts();
for (Product cn : products) {
String log = "Id: "+cn.getID_product()+" ,Name: " + cn.getName_product();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
break;
}
}
Hello everyone I have a problem in regards with the deletion or hiding of list in a list view something like .hide() in javascript . I know there are lots of answers here about it but it seems It didn't answer my problem. To explain clearly, below is some part of my code.
package sample.wew.wew;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QuestionsSent extends Fragment {
private static final String TAG = "Question";
private static List questions;
protected ListAdapter adapter;
ListView theList;
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
Cursor cursor = msg_db.FetchQuestion("S");
String[] fromFieldNames = new String[] { "msg_from_user", "msg_message" };
int[] toViewIDs = new int[] { R.id.tvMessage, R.id.tvMessageSender };
adapter = new QuestionsCursorAdapter(getActivity(), // Context
R.layout.question_detail, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
theList = (ListView) view.findViewById(R.id.list);
theList.setAdapter(adapter);
theList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/*
Log.v(TAG, ": NAAY GI CLICK");
Intent intent = new Intent(getActivity(), Sent_details.class);
Cursor cursor = (Cursor) adapter.getItem(position);
Log.d("TAG", "" + adapter.getItem(position));
intent.putExtra("MESSAGE_ID", cursor.getString(cursor.getColumnIndex("msg_message")));
startActivity(intent);
*/
// HERE IS WHERE I WANT TO PUT MY CODE TO DELETE OR HIDE A LIST
}
});
if(adapter.isEmpty()){
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No Sent Questions");
}
return view;
}
}
Here you can do something like this it will ask you in the form of dialogue box to weather delete the record or not and after clicking yes it will delete the record. Hope this helps you ...
userList.setOnItemLongClickListener(new OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,final int arg2, long arg3)
{
build = new AlertDialog.Builder(HomePage.this);
build.setTitle("Delete " + FirstName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), FirstName.get(arg2) + " " + LastName.get(arg2) + " is deleted.", 3000).show();
dataBase = mHelper.getWritableDatabase();
dataBase.delete(DatabaseActivity.TABLE_NAME, DatabaseActivity.KEY_ID + "=" + userId.get(arg2), null);
dataBase.close();
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
put these lines in your onlistitemclick
int count = youradapter.getCount();
for (int i = count-1; i >= 0; i--)
{
adapter.remove(adapter.getItem(i).postion);
}
and add this line in belooo
adapter.notifyDataSetChanged();
This is my code for click on a customlistview. When I click on the header, it works but after header its not working. CustomAdapter is another class in my App where I have defined header and all variables of listview. Please help me to resolve this problem.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ProbabilityConditional extends Activity {
String htmlcodefor_root = "√", htmlcodefor_multiply = "×",
htmlcodefor_divide = "÷", htmlcodefor_underroot = "�B3";
ListView listView1;
String htmlcodefor_space = " ", htmlcodefor_pi = "Π",
htmlcodefor_largespace = " ";
String htmlcodefor_implies = "⇒";
String htmlcodefor_i = "ᵢ";
String htmlcodefor_angle = "θ";
String htmlcodefor_overline = "‾", htmlcodefor_plusminus = "±";
// TextView txtv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// txtv = (TextView)findViewById(R.id.txtTitle);
// txtv.setText(Html.fromHtml("1.(constant)<sup><small>0</></> = 1"));
listView1 = (ListView) findViewById(R.id.listView1);
CustomAdapter.formula_one_custom_adapter_class_var = Html.fromHtml("1 ");
CustomAdapter.formula_two_custom_adapter_class_var = Html.fromHtml("2 ");
CustomItemCall formula_data[] = new CustomItemCall[] {
new CustomItemCall(CustomAdapter.formula_one_custom_adapter_class_var),
new CustomItemCall(CustomAdapter.formula_two_custom_adapter_class_var),
};
CustomAdapter adapter = new CustomAdapter(this,R.layout.listview_item_row, formula_data);
View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
Toast.makeText(ProbabilityConditional.this,position + " " , Toast.LENGTH_LONG).show();
// When clicked, show a toast with the TextView text
if (position == 1) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalDiscrete.class));
} if (position == 2) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalContinuous.class));
}
}
});
}
}
make your listview focusable true add these line in your xml android:focusable="true"
and make other item of list make false android:focusable="false "
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
Toast.makeText(ProbabilityConditional.this,position + " " , Toast.LENGTH_LONG).show();
// When clicked, show a toast with the TextView text
if (position == 1) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalDiscrete.class));
} if (position == 2) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalContinuous.class));
}
}
});
write code like this, simple way:-
ListView list;
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id)
{
//if in future you need to start a new activity
//then add below line also in your activity
Intent in = new Intent(MainActivity.this, SecondActivity.class);
startActivity(in);
}
});
Here is my buttonAdapter class that i think is accurate:
package com.example.test;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
public String [] fName = { "File 1", "File 2", "Roflcopters"};
// Gets the context so it can be used later
public ButtonAdapter(Context c) { mContext = c; }
// Total number of things contained within the adapter
public int getCount () { return 8; }
// Require for structure, not really used in my code.
public Object getItem (int position) { return null; }
// Require for structure, not really used in my code. Can be used to get the id of an item in the adapter for manual control.
public long getItemId (int position) { return position; }
public View getView (int position, View convertView, ViewGroup parent){
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn = new Button (mContext);
btn.setLayoutParams (new GridView.LayoutParams (190, 190));
btn.setPadding (1, 1, 1, 1);
} else {
btn = (Button) convertView;
}
// btn.setText(filesnames[position]);
// filenames is an array of strings
//btn.setTextColor (Color.WHITE);
//btn.setBackgroundResource (R.drawable.sample_2);
//btn.setBackgroundColor (Color.BLACK);
btn.setHighlightColor(Color.GREEN);
btn.setId (position);
return btn;
}
}
Here is my home class. I can't get the onItemClick to work out. What am I doing wrong here:
package com.example.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
public class home extends Activity implements OnItemClickListener {
public final static String EXTRA_MESSAGE1 = "com.example.text.MESSAGE";
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_home);
GridView gridview = (GridView) findViewById (R.id.gridview);
gridview.setAdapter (new ButtonAdapter (this));
/*gridview.setOnItemClickListener (new OnItemClickListener () {
public void onItemClick (AdapterView <?> parent, View v, int position, long id) {
Toast.makeText (home.this, "" + position, Toast.LENGTH_LONG).show ();
Intent intent = new Intent (this, alarm.class);
String message = "Position:" + position;
intent.putExtra(EXTRA_MESSAGE1, message);
startActivity (intent);
}
});
* */
}
#Override
public void onItemClick (AdapterView <?> parent, View v, int position, long id) {
Intent intent = new Intent (this, alarm.class);
String message = "Position:" + position;
intent.putExtra(EXTRA_MESSAGE1, message);
startActivity (intent);
}
}
The onItemClick doesn't work and neither does the commented 'setOnItemClickListener' when it isn't commented out and 'onItemClick' is commented. What am I doing wrong?
If GridView, ListView have click able controls like BUtton, then onItemClick will not fired.
You need to implement Button Click listener in your getView method of the adapter.
like
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
if (convertView == null) { // if it's not recycled, initialize some
// attributes btn = new Button (mContext);
btn.setLayoutParams(new GridView.LayoutParams(190, 190));
btn.setPadding(1, 1, 1, 1);
} else {
btn = (Button) convertView;
} // btn.setText(filesnames[position]); // filenames is an array of
// strings //btn.setTextColor (Color.WHITE);
// btn.setBackgroundResource (R.drawable.sample_2);
// btn.setBackgroundColor (Color.BLACK);
btn.setHighlightColor(Color.GREEN);
btn.setId(position);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Handle the click here
}
});
return btn;
}
You can add this line in the root layout of GridView items:
android:descendantFocusability="blocksDescendants"
Then onItemClickListener.onItemClick() will not fire when you tap on subviews which OnClickListener has been defined for them separately.
I've tested that Set Button.onClickListener() (in API 15) won't solve the problem.
So the GridView will not trigger onItemClick if it contains clickable views.
You can use ImageView instead Button.
i have the same problem when i was trying to implement onitemclick on gridview where filled with button. Because the button is stealing the focus of each space on gridview, you have to give the inflated button android:focusable="false" . however, the button is taking up almost entire space inside a grid, so you have to click the very edge of the button to trigger onitemclick call-back. i am suggesting you can set onclick or use image and designe it like a button.