OnClick for Right Drawable in gridview items (EDITED) - android

How can i perform an Onclick functionality for right drawable?
I have a gridview item list in which i set a right drawable to each item so that when user input something in editText then that right drawable will show in background and that drawable is delete icon so i want to perform onClick listener for that drawable only so that when user taps on that delete drawble then action is performed. I write the following code but its not working
keywordslist.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(final View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (keywordslist.getRight() - keywordslist.getPaddingRight())) {
new AlertDialog.Builder(context)
.setMessage("Remove " + ((TextView) v).getText().toString() + "?")
.setNeutralButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DBkeyword dbkey = new DBkeyword(context);
SQLiteDatabase dbw = dbkey.getWritableDatabase();
String deleteKeyword = "delete from " + "screenedkeywords" + " where " + "keywords" + " = \"" + ((TextView) v).getText().toString() + "\"";
dbw.execSQL(deleteKeyword);
dbw.close();
DisplayKeywords();
}
});
return true;
}
}
return false;
}
});

You have to notify your adapter that the data has changed.
customGridAdapter.notifyDataSetChanged();

I'm not 100 % sure, but shouldn't there be a
ArrayAdapter.getItemCount()
Maybe you didn't change the returning value from 0 to data.size().

Related

Pop up Menu functions for ReyclerView Item Android Studio

I'm implementing cancel and enable functions for my ReyclerView using a Pop up Menu that calls a backend API that interacts with the Database. The API works fine. However, the functions update the last Item on the List as opposed to the one selected. How do I go about this?
I tried to get the Id from the Model definition but also failed. It returned the Id for the last Item.
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
final MyHolder myHolder= (MyHolder) holder;
current = dataErrand.get(position);
myHolder.service.setText(current.errandservice);
myHolder.date.setText("Date: " + current.erranddate);
myHolder.time.setText("Time: " + current.errandtime);
myHolder.phone.setText("Phone: " + current.errandphone);
myHolder.location.setText("Location: " + current.errandlocation);
myHolder.status.setText("status: " + current.errandstatus);
myHolder.id.setText("Id: "+current.getErrandid());
myHolder.options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(context, myHolder.options);
popup.inflate(R.menu.errand_options);
Menu popMenu = popup.getMenu();
if(current.errandstatus == "Active"){
popMenu.findItem(R.id.errand_reactivate).setVisible(false);
popMenu.findItem(R.id.errand_cancel).setVisible(true);
}
if (current.errandstatus == "Canceled"){
popMenu.findItem(R.id.errand_cancel).setVisible(false);
popMenu.findItem(R.id.errand_reactivate).setVisible(true);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int menuId = item.getItemId();
if(menuId == R.id.errand_cancel){
//handle menu1 click
//return true;
Toast.makeText(context, " "+current.getErrandid(), Toast.LENGTH_LONG).show();
changeStatus = new ChangeStatus(context);
isChanged = changeStatus.makeChange(current.errandid,0 );
if(isChanged == true){
current.errandstatus = "Canceled";
myHolder.status.setText("status: " + current.errandstatus);
}
//return true;
}
if(menuId ==R.id.errand_reactivate){
Toast.makeText(context, " "+current.getErrandid(), Toast.LENGTH_LONG).show();
changeStatus = new ChangeStatus(context);
isChanged = changeStatus.makeChange(current.errandid, 1);
if(isChanged == true){
current.errandstatus = "Active";
myHolder.status.setText("status: " + current.errandstatus);
}
//return true;
}
return false;
}
});
popup.show();
}
});
OnMenuItemClick should forward the Item Id and the expected change; as either 1 for activate and 2 for cancel, to the backend API.enter image description here
Your current variable will be overridden at every onBindViewHolder call.
You should store the id with your ViewHolder, for example:
holder.options.setTag(position);
and then retrieve the position in the onclick method for example:
int pos = (int) v.getTag();
Hope it helps.

Calling notifyDataSetChanged in my onFocusChangedListener causes focus to freak out in my ListView

I have a ListView which has multiple EditTexts per item. When I change an EditText on one item, I'd like it to affect the text on the next item. I'm using an onFocusChanged listener and I can successfully update the underlying data, but My actual focus is lost (and my cursor ends up in weird places). Please review my code and offer any insight. I've been banging my head about this for a while.
Note:
I am not recycling items using a holder, as this was giving me odd behavior and my performance is not suffering. Every time I've tried re-enabling the recycling, things get messier.
I have overriden hasStableIds to return true, but it doesn't seem to make any difference.
Assigning the Listener:
MyFocusChangeListener myFocusListener = new MyFocusChangeListener(myItem, position);
holder.et_min.setOnFocusChangeListener(myFocusListener);
Defining the Listener:
private class MyFocusChangeListener implements View.OnFocusChangeListener{
private EditText et;
private EditText curView;
private ScaleItem item;
private Integer pos;
public MyFocusChangeListener(ScaleItem item, Integer pos){
this.item = item;
this.pos = pos;
}
#Override
public void onFocusChange(View v, boolean hasFocus){
if(!hasFocus){
et = (EditText) v;
System.out.println("EditText lost focus on row: " + et.getText().toString() + " et id: " + et.getId());
if(pos < data.size()){
data.get(pos + 1).setMax(Double.valueOf(et.getText().toString()));
notifyDataSetChanged();
System.out.println("Updated dataset and called notifyDataSetChanged()");
}
} else {
et = (EditText) v;
if(et != null)
System.out.println("EditText just RECEIVED focus on row : " + et.getText().toString() + " et id: " + et.getId());
}
}
}
This is the console output I get, if I enter the activity, click field A, and then click field B.
Notice:
Each EditText (regardless of row) has the same ID (I think this is expected)
The only change I'm making is to the underlying data. In fact, I have the same issue if I change nothing but call notifyDataSetChanged.
The target field loses focus, I've no idea why.
TL;DR - Calling notifyDataSetChanged() in my onFocusChangedListener causes focus to freak out in my ListView.
See? The cursor is drunk.
If you focus a EditText in ListView get position value, after updating ListView redrawn and automatically it will select last position.
Step 1:
if (_Curserposition == position) {
holder.textViewStake.setFocusableInTouchMode(true);
//holder.textViewStake.clearFocus();
holder.textViewStake.requestFocus();
holder.textViewStake.setSelection(holder.textViewStake.getText().toString().length());
}
Step 2:
holder.textViewStake.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
_Curserposition = position;
Log.d(">>>", "setOnFocusChangeListener" + _Curserposition);
/*
//showVirtualKeyboard(con_text, v);
// holder.textViewStake.requestFocus();
InputMethodManager imm = (InputMethodManager) activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (hasFocus) {
imm.showSoftInput(holder.textViewStake, InputMethodManager.SHOW_FORCED);
} else {
imm.hideSoftInputFromWindow(holder.textViewStake.getWindowToken(), 0);
}*/
}
});
Step 3:
holder.textViewStake.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
betlist_view.setFocusable(false);
if (s.length() > 0) {
try {
if (Integer.parseInt(holder.textViewStake.getText().toString()) > 0) {
int _Stackamt = Integer.parseInt(holder.textViewStake.getText().toString());
int _picknumber = arrayDailyGameDrawList.get(position).getID();
//Log.d(">>>", "_picknumber" + position + "-" + arrayDailyGameDrawList.get(position).getBetNumberID() + "-" + Common.DrawId + "-" + _Stackamt + "-" + arrayDailyGameDrawList.get(position).getBetNumberID());
AddUpdateDailyGameNumberIntoList(
position,
2,
arrayDailyGameDrawList.get(position).getBetNumberID(),
Common.DrawId,
_Stackamt,
arrayDailyGameDrawList.get(position).getBetNumberID()
);
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);*/
}
} catch (Exception e) {
}
} else {
holder.textViewStake.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});

ViewPager offsets cursor position

I have a situation similar to this ViewPager. Getting wrong cursor in SimpleCursorAdapter and this ViewPager Cursor positon but the questions had no
applicable answer.
Situation
I am loading the views in my viewpager from a database (cursor). When I set the text for the items (Buttons, TextViews etc) it does this with the correct cursor (in the expected position).
But when i try to button.getText() it shows me the text from the next position in the database (same with buttons etc). If the user swipes forward, the cursor returns values in the next position and if the user swipes backward, it returns values in the previous position
So at position x swiping forward returns cursor at position x + 1 and swiping backwards returns cursor at postion x - 1.
How can i solve this? This is my PagerAdapter.instantiateItem
public Object instantiateItem(View view, int position) {
cursor.moveToPosition(position);
int cus = cursor.getPosition();
Log.d(DBHelper.TAG, Integer.toString(cus) + " current cursor position ");
final ViewPager pager = (ViewPager) view.findViewById(R.id.pager_nav);
ScrollView layout = (ScrollView) inflater.inflate(R.layout.question_activity, null);
if (cursorCategory != null && cursorCategory.moveToFirst()){
String s = cursorCategory.getString(cursorCategory.getColumnIndex("name"));
((TextView)layout.findViewById(R.id.text_category)).setText(s);
}
Typeface tpf = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf");
String text = cursor.getString(cursor.getColumnIndex("question_text"));
TextView question_text = (TextView)layout.findViewById(R.id.text_question);
question_text.setText(text);
Log.d("question_text", question_text.getText() + " " + position + " " + text);
question_text.setTypeface(tpf);
final String qPos = Integer.toString(position + 1) + ".";
TextView question_position = (TextView) layout.findViewById(R.id.text_position);
question_position.setText(qPos);
question_position.setTypeface(tpf);
this.rightAnswer = cursor.getString(cursor.getColumnIndex(DBHelper.RIGHT_ANSWER));
this.wrongAnswer1 = cursor.getString(cursor.getColumnIndex(DBHelper.WRONG_ANSWER1));
this.wrongAnswer2 = cursor.getString(cursor.getColumnIndex(DBHelper.WRONG_ANSWER2));
optionsArray = new ArrayList<String>();
optionsArray.clear();
optionsArray.add(this.rightAnswer);
optionsArray.add(this.wrongAnswer1);
optionsArray.add(this.wrongAnswer2);
Collections.shuffle(optionsArray);
option1 = (Button) layout.findViewById(R.id.button_option1);
option1.setText((CharSequence) this.optionsArray.get(0));
option2 = (Button) layout.findViewById(R.id.button_option2);
option2.setText((CharSequence) this.optionsArray.get(1));
option3 = (Button) layout.findViewById(R.id.button_option3);
option3.setText((CharSequence) this.optionsArray.get(2));
if (this.optionsArray.get(0).equalsIgnoreCase(this.rightAnswer)) {
this.option1.setTag(DBHelper.RIGHT_ANSWER);
} else if (!this.rightAnswer.equalsIgnoreCase((String) this.optionsArray.get(0))) {
this.option1.setTag("wrong");
}
if (this.rightAnswer.equalsIgnoreCase((String) this.optionsArray.get(1))) {
this.option2.setTag(DBHelper.RIGHT_ANSWER);
} else if (!this.rightAnswer.equalsIgnoreCase((String) this.optionsArray.get(1))) {
this.option2.setTag("wrong");
}
if (this.rightAnswer.equalsIgnoreCase((String) this.optionsArray.get(2))) {
this.option3.setTag(DBHelper.RIGHT_ANSWER);
} else if (!this.rightAnswer.equalsIgnoreCase((String) this.optionsArray.get(2))){
this.option3.setTag("wrong");
}
private int getItem(int i) {
return i += pager.getCurrentItem();
}
});
option1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String Tag = option1.getTag().toString();
Toast.makeText(context, Tag + " " + option1.getText(), Toast.LENGTH_SHORT).show();
}
});
option2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String Tag = option2.getTag().toString();
Toast.makeText(context, Tag + " " + option2.getText(), Toast.LENGTH_SHORT).show();
}
});
option3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String Tag = option3.getTag().toString();
Toast.makeText(context, Tag + " " + option3.getText(), Toast.LENGTH_SHORT).show();
}
});
}
And my onLoadFinished()
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
switch (loader.getId()) {
case QUESTION_TEXT:
Log.d(" Selection Position", " Selection Position" + selcectionPosition );
Log.d(" Activity Position", cursor.getPosition() + " Activity Position");
mAdapter.swapCursor(cursor);
mAdapter.notifyDataSetChanged();
pager.setCurrentItem(selcectionPosition, true);
break;
}
}
Hoping to get some help.
Disclaimer: It might not be the solution to your problem.
I faced the same problem.
So after reading what you wrote, I searched around for something that would help us.
I solved it by using this: How do you get the current page number of a ViewPager for Android?
On my project, I had a button on each page, that on click would trigger a dialog, this dialog would then get a string from the current position of a cursor.
The position on the cursor didn't match the current page being displayed, because, ViewPager changes the cursor's position to get data to preload pages.
So you need to force the the cursor to move to the correct position, the one you're viewing.
To do that, you use cursor.moveToPosition(viewpager.getCurrentItem()).
To make sure the cursor follows what you are viewing.
I hope this helps you.

DialogFragment OnClickListener strange Cursor behavior

I am using the code below in a class extending DialogFragment.
Before adding the buttons I move a cursor to a certain position (see setDataFromCursor()) The strange thing is, that the position has changed when trying to get the position again in the OnClickListener of the positive button.
I added some Log output which proves that. Does anybody know why that happens?
Thanks for your help!
Edit: In the debugger it is visible too. I step forward a few steps and the cursor position changes without calling moveToPosition.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Log.v(TAG, "onCreateDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
view = inflater.inflate(R.layout.query_tab_dialog_add_operation,
null);
name = (TextView) view.findViewById(R.id.editTextOPName);
cimclass = (TextView) view.findViewById(R.id.editTextCIMclass);
setDataFromCursor();
builder.setView(view)
.setTitle(
R.string.querytabfragment_dialog_editOperation_title)
.setPositiveButton(R.string.apply,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
nameStr = name.getText().toString();
cimclassStr = cimclass.getText().toString();
Log.d(TAG,
"cursor position: "
+ cursor.getPosition());
int id = cursor.getInt(0);
Log.d(TAG, "cursor on item: " + id);
// update affected row
queryDBHelper.editCIMQuery(id, nameStr,
cimclassStr);
Log.d(TAG, "query edited. id: " + id
+ " name: " + nameStr
+ " cimclass: " + cimclassStr);
cursor.requery();
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
EditOperationDialogFragment.this
.getDialog().cancel();
}
});
return builder.create();
}
private void setDataFromCursor() {
cursor.moveToPosition(cursorPosition);
name.setText(cursor.getString(1));
cimclass.setText(cursor.getString(2));
}
The code that you posted doesn't change the Cursor's position anywhere else.
However, if cursor references the same Cursor used in a CursorAdapter bound to a ListView then when the Dialog is drawn it probably obscures part of a ListView forcing the ListView to redraw. This definitely changes the position.
Solution: Either use moveToPosition() again in the OnClickListener or fetch an independent Cursor.

Can I do onTap that doesn't require a longpress, but still have longpress enabled for other events?

Currently I have a series of markers on a google map. I want to be able to get the latitude and longitude from anywhere I longclick on the map and I want to open a message box dialog when I quick click on a marker. My issue is that by setting up longpress to work it makes it so my onTap function only gets called when I longclick. Is it possible for longlick to work only when I'm not clicking on a marker?
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
return gestureScanner.onTouchEvent(event);
//return false;
}
////////////////////////////////////
// Handle the clicking of a marker
//
////////////////////////////////////
#Override
protected boolean onTap(int index)
{
System.out.println("OnTap");
OverlayItem item = mOverlays.get(index);
int localLat = item.getPoint().getLatitudeE6();
int localLong = item.getPoint().getLongitudeE6();
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
// Get the titles
dialog.setTitle(item.getTitle());
// Get the text for the message
//dialog.setMessage(item.getSnippet());
dialog.setMessage("Latitude: " + localLat + "\nLongitude: " + localLong);
dialog.setNeutralButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
}
});
dialog.show();
return true;
}
#Override
public void onLongPress(MotionEvent e)
{
long downTime = e.getDownTime();
System.out.println("Down time: " + downTime);
System.out.println("LongPress Registered");
GeoPoint p = localMapView.getProjection().fromPixels((int) e.getX(), (int) e.getY());
System.out.println("Latitude = " + p.getLatitudeE6() + " Longitude: " + p.getLongitudeE6());
}
Here's something similar here that might be helpful. You can also override the onTouchEvent() of the Overlay to handle each.

Categories

Resources