I have a recyclerview. After setting adapter, user should be reorder their list and save it. And afterwards it should be populate like saved one. But onclicking list items, it color has to change and one of item will open a popup. I've write my codes, but when i add both onclick and ontouch, neither of them worked. If i comment one of them, they work fine. How can i solve this?
holder.itemView.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
touchHelper.startDrag(holder);
}
return false;
});
holder.clData.setOnLongClickListener(view -> {
row_index = position;
notifyDataSetChanged();
return true;
});
if (row_index == position) {
holder.clData.setBackgroundColor(context.getResources().getColor(R.color.blue_back));
holder.txtAmount.setTextColor(Color.WHITE);
} else {
holder.clData.setBackgroundColor(context.getResources().getColor(R.color.darkestGrey));
holder.txtAmount.setTextColor(context.getResources().getColor(R.color.blue_current));
}
/// https://github.com/sjthn/RecyclerViewDemo/blob/advanced-usecases/app/src/main/java/com/example/srijith/recyclerviewdemo/SwipeAndDragHelper.java
////// My Adapter
AdapterDatas adapter = new AdapterDatas (context, lstDatas);
SwipeAndDragHelper swipeAndDragHelper = new SwipeAndDragHelper(adapter);
ItemTouchHelper touchHelper = new ItemTouchHelper(swipeAndDragHelper);
adapter.setTouchHelper(touchHelper);
rvDatas.setAdapter(adapter);
touchHelper.attachToRecyclerView(rvDatas);
Related
I have three text input layouts in my activity, I apply a listener on them and it changes background color when I click on it .but need to click again if I want to click the other two .my question is that how I implement such type of logic that when it 1st clicked and I click on one of the other two, the first one clickable color disappear and 2nd one or third one clicked and its background color change and same for others
View.OnClickListener listener = new View.OnClickListener() {
#SuppressLint("NonConstantResourceId")
#Override
public void onClick(View v) {
if (v.getId() == R.id.textViewLoseWeightSubtitle) {
if (mStateChanged) {
v.setBackgroundResource(R.drawable.textview_after_click);
// mLoseWgt.setTextColor(Color.WHITE);
mStateChanged = false;
mFittedToned.setClickable(false);
mBuildMuscle.setClickable(false);
} else {
v.setBackgroundResource(R.drawable.textview_outline_style);
//mLoseWgt.setTextColor(Color.parseColor("#363C60"));
mStateChanged = true;
mFittedToned.setClickable(true);
mBuildMuscle.setClickable(true);
}
}
if (v.getId() == R.id.textViewBuildMusclesSubtitle) {
if (mStateChanged) {
v.setBackgroundResource(R.drawable.textview_after_click);
// mLoseWgt.setTextColor(Color.WHITE);
mStateChanged = false;
mLoseWgt.setClickable(false);
mFittedToned.setClickable(false);
} else {
v.setBackgroundResource(R.drawable.textview_outline_style);
//mLoseWgt.setTextColor(Color.parseColor("#363C60"));
mStateChanged = true;
mLoseWgt.setClickable(true);
mFittedToned.setClickable(true);
}
}
if (v.getId() == R.id.textViewFittedAndTonedSubtitle) {
if (mStateChanged) {
v.setBackgroundResource(R.drawable.textview_after_click);
// mLoseWgt.setTextColor(Color.WHITE);
mStateChanged = false;
mLoseWgt.setClickable(false);
mBuildMuscle.setClickable(false);
} else {
v.setBackgroundResource(R.drawable.textview_outline_style);
//mLoseWgt.setTextColor(Color.parseColor("#363C60"));
mStateChanged = true;
mLoseWgt.setClickable(true);
mBuildMuscle.setClickable(true);
}
}
}
};
mLoseWgt.setOnClickListener(listener);
mBuildMuscle.setOnClickListener(listener);
mFittedToned.setOnClickListener(listener);
}
What you need is a onFocusChangedListener(). It gives a callback with a boolean which can be used to identify whether the current view is selected or not.
Declare it as:
View.OnFocusChangeListener listener = new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setBackgroundResource(R.drawable.textview_after_click);
// mLoseWgt.setTextColor(Color.WHITE);
} else {
v.setBackgroundResource(R.drawable.textview_outline_style);
//mLoseWgt.setTextColor(Color.parseColor("#363C60"));
}
}
});
Set it as:
mLoseWgt.setOnFocusChangeListener(listener);
mBuildMuscle.setOnFocusChangeListener(listener);
mFittedToned.setOnFocusChangeListener(listener);
That's it. Your other code seems redundant. For EditText specific functions, you can typecast the view provided by onFocusChange().
I have a list of timezones that gets added to a recycler view. However, my main list in the activity checks properly but when I use the search and the list condenses and I click the checkbox it will not show the checkmark. However, in debug, the value is set to true when clicked and it will still add it into the recycler view properly.
I have tried looking online but there was no solution for this specific problem.
#Override
public void onBindViewHolder(#NonNull final TimezoneViewHolder holder, final int position) {
// Initialize tools
final Timezone_Item currentTimezoneItem = timezoneList.get(position);
int pos = currentTimezoneItem.getId();
final int tzID = --pos;
holder.mChkboxSelect.setText(currentTimezoneItem.getValue());
holder.mUTCCode.setText(currentTimezoneItem.getName());
// This is the solution for... Clicking the checkbox once would select multiple timezones. Not with this.
if(selectedTimezones.get(position)){
holder.mChkboxSelect.setChecked(true);
currentTimezoneItem.setIsSelected(true);
}else{
holder.mChkboxSelect.setChecked(false);
currentTimezoneItem.setIsSelected(false);
}
// Manually activate the clicks in checkbox
holder.mChkboxSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
holder.mChkboxSelect.setChecked(false);
}else {
currentTimezoneItem.setIsSelected(true);
holder.mChkboxSelect.setChecked(true);
}
if(TimezonePickerActivity.isSearching){
selectedTimezones.put(currentTimezoneItem.getId() - 1, currentTimezoneItem.getIsSelected());
}else {
selectedTimezones.put(tzID, currentTimezoneItem.getIsSelected());
}
notifyDataSetChanged();
}
});
}
This is my Search filter...
private Filter SearchFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence searchText) {
List<Timezone_Item> filteredList = new ArrayList<>();
if (searchText == null || searchText.length() == 0) {
TimezonePickerActivity.isSearching = false;
filteredList.addAll(timezoneListFull);
} else {
String filterPattern = searchText.toString().toLowerCase().trim();
TimezonePickerActivity.isSearching = true;
for (Timezone_Item item : timezoneListFull) {
if (item.getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence searchText, FilterResults results) {
timezoneList.clear();
timezoneList.addAll((List) results.values);
notifyDataSetChanged();
}
};
This is my code to add the selected timezone into the recycler view
fabAddTimezone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { SparseBooleanArray selectedTimezones = Timezone_RVAdapter.selectedTimezones;
// Filter out false values
for (int i = 0; i < selectedTimezones.size(); i++) {
if(!selectedTimezones.valueAt(i)){
selectedTimezones.removeAt(i);
selectedTimezones.delete(i);
}
}
// Take filtered values and find its index to grab text and UTC code
for (int i = 0; i < selectedTimezones.size(); i++) {
// Get the position(Key) which is actually the Timezone_Item ID
int position = selectedTimezones.keyAt(i);
// Create new clock item to add into list
Clock_Item clockItem = new Clock_Item(
Timezone_RVAdapter.timezoneListFull.get(position).getName(),
Timezone_RVAdapter.timezoneListFull.get(position).getValue()
);
// Add clock to a list
mClockList.add(clockItem);
}
// Save clock list
sharedPrefs.SaveClockList(mClockList);
// Go back to main menu. Clock list should automatically load once activity boots
finish();
}
});
There is a possibility that the below block is always true
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
//Calling the below statement is irrelevant inside onClick of itself
//because when inside here checkbox can never be checked
holder.mChkboxSelect.setChecked(false);
}
remove or comment out every line statement calling .setChecked on mChkboxSelect and allow android handle the state. You can control the state of a checkbox but not inside it's onClick event because clicking on a checkbox automatically changes the state.
I'm using a ListView in my project and wanted to add a context menu to each list item so that each can be removed individually. When using the following code this appears to work just fine:
postList.setCellFactory(lv -> {
ListCell<Result> cell = new ListCell<>();
ContextMenu contextMenu = new ContextMenu();
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
#Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
cell.textProperty().bind(stringBinding);
MenuItem deleteItem = new MenuItem();
deleteItem.textProperty().bind(Bindings.format("Delete item"));
deleteItem.setOnAction(event -> postList.getItems().remove(cell.getItem()));
contextMenu.getItems().addAll(openPermalink, openSubreddit, openURL, deleteItem);
cell.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -> {
if (isNowEmpty) {
cell.setContextMenu(null);
} else {
cell.setContextMenu(contextMenu);
}
});
return cell;
});
However, after clearing the post list - although the items appear to be removed - when another is added all of the removed items re-appear and the item to be added is not displayed.
Any items what could be causing this? It only happens when I set the cell factory and is fine otherwise.
I recorded a small gif to help better explain the issue:
Thank you!
Edit: It appears that the issue is mainly to do with this segment
StringBinding stringBinding = new StringBinding() {
{
super.bind(cell.itemProperty().asString());
}
#Override
protected String computeValue() {
if (cell.itemProperty().getValue() == null) {
return "";
}
return cell.itemProperty().getValue().getTitle();
}
};
As is seems that even though the items are there they have an empty display title
If you use ListCell.updateItem() workflow instead of the StringBinding it should work:
ListCell< Result > cell = new ListCell< Result >() {
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getValue());
} else {
setText("");
}
}
};
Your binding workflow seems to create an unnecessary dependency which blocks deletion.
P.S.: why do you use binding for static text in deleteItem? Just assign the value directly:
MenuItem deleteItem = new MenuItem();
deleteItem.setText("Delete item");
I have a news list. I use this;
ListAdapter adapter = new SimpleAdapter(this, getXmlData(URL,KEY_ITEM,KEY_COLUMN),
R.layout.news_list,
new String[] { KEY_COLUMN[1],KEY_COLUMN[0] }, new int[] {
R.id.name,R.id.list_image});
KEY_COLUMN[1] is caption.
KEY_COLUMN[0] is id value. It must be hidden.
My problem is R.id.list_image.
I can set KEY_COLUMN[0] to src of R.id.list_image. But i want to set KEY_COLUMN[0] to contentDescription of R.id.list_image.
Can you help? I don't use lazyadaptor etc.
EDİT:
i have new problem. if i need 2 data for imageview, how can i use?
ListAdapter adapter = new SimpleAdapter(this, getXmlData(URL,KEY_ITEM,KEY_COLUMN),
R.layout.news_list,
new String[] { KEY_COLUMN[1],KEY_COLUMN[0],KEY_COLUMN[2] }, new int[] {
R.id.name,R.id.list_image,R.id.list_image});
KEY_COLUMN[0] set to setContentDescription of R.id.list_image
KEY_COLUMN[2] set to src of R.id.list_image
You'll need to use custom binder to do this. It can be accomplished with adding something like this in the next line:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// Log.v(TAG, "Binding view: " + view);
if (view.getId() == R.id.list_image) {
((ImageView) view).setContentDescription((CharSequence)) data);
return true;
}
return false;
}
});
My app has an options menu that is available in almost all Activities, which was created by implementing onCreateOptionsMenu(). But in one Activity there is a PopupWindow, and when this PopupWindow has focus (required for proper functioning) tapping the menu button does not bring up the options menu.
PopupWindows do not have an onCreateOptionsMenu() function. Is there some other way to add an options menu to a PopupWindow?
Alternatively, is there a way to get the options menu from the Activity behind it to show up when the user taps the menu button?
I solved this by intercepting the menu key and calling openOptionsMenu() on the activity. Here is the key listener:
OnKeyListener mMenuKeyListener = new OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_MENU) {
activity.openOptionsMenu();
return true;
} else {
return false;
}
}
};
I think you have to add this key listener to every view in the PopupWindow to get it to work, so I wrote a function to do that:
public void setupMenuKeyListenerRecursive(View v) {
if (v != null) {
try {
ViewGroup viewGroup = (ViewGroup)v;
int childCount = viewGroup.getChildCount();
for (int index = 0; index < childCount; index++) {
View child = viewGroup.getChildAt(index);
setupMenuKeyListenerRecursive(child);
}
} catch (Exception e) {
}
v.setOnKeyListener(mMenuKeyListener);
}
}