Android: Swipe to delete row from list view - android

I am developing an application in which i am having a custom list view with custom adapter. The adapter contains image view, text view and other view. I want to swipe the list item to delete it from list. The link i refereed are as :
Ans having High vote
One row is looks like.
1 = Image view.
2 = Text view
The swipe is working but it is not smooth. When i swipe at bottom that time row deleted else the swipe is not properly working.
Please suggest me what i am missing or what changes i need to do or add or apply.

package com.example.android.swipedismiss;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends ListActivity {
ArrayAdapter<String> mAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up ListView example
String[] items = new String[20];
for (int i = 0; i < items.length; i++) {
items[i] = "Item " + (i + 1);
}
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
new ArrayList<String>(Arrays.asList(items)));
setListAdapter(mAdapter);
ListView listView = getListView();
// Create a ListView-specific touch listener. ListViews are given special treatment because
// by default they handle touches for their list items... i.e. they're in charge of drawing
// the pressed state (the list selector), handling list item clicks, etc.
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mAdapter.remove(mAdapter.getItem(position));
}
mAdapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
// Set up normal ViewGroup example
final ViewGroup dismissableContainer = (ViewGroup) findViewById(R.id.dismissable_container);
for (int i = 0; i < items.length; i++) {
final Button dismissableButton = new Button(this);
dismissableButton.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
dismissableButton.setText("Button " + (i + 1));
dismissableButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Clicked " + ((Button) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
// Create a generic swipe-to-dismiss touch listener.
dismissableButton.setOnTouchListener(new SwipeDismissTouchListener(
dismissableButton,
null,
new SwipeDismissTouchListener.DismissCallbacks() {
#Override
public boolean canDismiss(Object token) {
return true;
}
#Override
public void onDismiss(View view, Object token) {
dismissableContainer.removeView(dismissableButton);
}
}));
dismissableContainer.addView(dismissableButton);
}
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Toast.makeText(this,
"Clicked " + getListAdapter().getItem(position).toString(),
Toast.LENGTH_SHORT).show();
}
}
full source code on githib and also tested

Related

Saved item's state in simple list item

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

Simple list item multiple choice not selecting items

I've created an array list and display it in a list view with simple list item multiple choice but i cannot check or tick the items on the list, when i click on the items nothing happens. Please check my code below and tell me what i am doing wrong.
package com.example.arrays;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
public class MainActivity extends Activity {
ListView showList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show = (TextView)findViewById(R.id.txtShow);
final Random generate = new Random();
showList = (ListView)findViewById(R.id.listView1);
final String[] myAttraction = new String[4];
myAttraction[0]= "Walter Sisulu National Botanical Garden ";
myAttraction[1]= "Coca-Cola Dome";
myAttraction[2]= "Promusica Theatre";
myAttraction[3]= "Unisa Science Campus";
Button arrays = (Button)findViewById(R.id.button1);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
}
});
showList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add a OnItemClickListener like this to check/uncheck the CheckedTextView when user click on an item
showList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// change the checkbox state
CheckedTextView checkedTextView = ((CheckedTextView)view);
checkedTextView.setChecked(!checkedTextView.isChecked());
}
});
change your code as following....
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
arrays.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*int random = generate.nextInt(4);
String display = myAttraction[random];
show.setText(display);*/
}
});
showList.setOnItemClickListener(new OnItemClickListener() {
public boolean onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "long clicked pos: " + pos, Toast.LENGTH_LONG).show();
return true;
}
});
Set choiceMode property of your list to multipleChoice. I'm implementing multiple choice list in such a way in my applications, and it surely works.
Change this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setAdapter(adapter);
To this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, myAttraction);
showList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
showList.setAdapter(adapter);
Just Add this line if you have a ListView and have selected simple_list_item_multiple_choice and you are unable to interact with the checkbox.
YourListViewName.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

AutoCompleteTextView OnItemClick position is always "0"

the adapter works fine, but i don't understand why the position in OnItemClick is always "0"
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int pos=position;
}
});
Don't ask me why, but the argument position in method OnItemClickListener.onItemClick holds the index relative to the AutoCompleteTextView's dropdown list, not the position in your adapter array (in your case regions)!
So, to find the item's real position you must get the string selected in the dropdown and find its index in the adapter array:
String[] regions = ct.getRegions();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, regions);
regionT.setAdapter(adapter);
regionT.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selected = (String) parent.getItemAtPosition(position);
int pos = Arrays.asList(regions).indexOf(selected);
}
});
I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:
public class Country extends Object {
public int id;
public Country(int id) {
this.id = id;
}
#NonNull
#Override
public String toString() {
switch (id) {
case 0:
return "Albania";
case 1:
return "Romania";
case 2:
return "Ucraina";
case 3:
return "Russia";
default:
return "Unknwon";
}
}
}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
new Country(0),
new Country(1),
new Country(2),
new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
int nItems = ada.getCount();
// default Country unknown
Country selItem = new Country(5);
if (nItems > 0) {
selItem = (Country) ada.getItem(0);
}
Log.d(TAG,
"onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
+ ", selItem.id=" + selItem.id);
}
});
...
Logs:
when the AutocompleteTextView value matches an item in the dropdown:
onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2
when the value is blank:
onClick(): nItems=4, selItem.name=Albania, selItem.id=0
when the value isn't blank but doesn't match any item in the dropdown:
onClick(): nItems=0, selItem.name=Unknown, selItem.id=5
You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.
I put this in a simple example and it works correctly for me. See below:
package com.example.autocompletetv;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
public class AutoCompleteActivity extends ListActivity {
public static final String TAG = AutoCompleteActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_complete);
String[] regions = {"One", "Two", "Three", "Four", "Five"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, regions);
this.setListAdapter(adapter);
this.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "postion was " + position);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_complete, menu);
return true;
}
}
When I click I get:
12-09 19:13:30.617: I/AutoCompleteActivity(1883): postion was 2
12-09 19:13:31.997: I/AutoCompleteActivity(1883): postion was 3
12-09 19:13:34.687: I/AutoCompleteActivity(1883): postion was 4
12-09 19:13:37.028: I/AutoCompleteActivity(1883): postion was 0

Click on item of customlist-view is not working

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 = "&#x221A", htmlcodefor_multiply = "&#xD7",
htmlcodefor_divide = "&#xF7", htmlcodefor_underroot = "&#00B3";
ListView listView1;
String htmlcodefor_space = "&#8194", htmlcodefor_pi = "&#928",
htmlcodefor_largespace = "&#8195";
String htmlcodefor_implies = "&#x21D2";
String htmlcodefor_i = "&#7522";
String htmlcodefor_angle = "&#952";
String htmlcodefor_overline = "&#x203E", htmlcodefor_plusminus = "&#177";
// 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);
}
});

Android Gridview and Button OnItemclick

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.

Categories

Resources