Shared Element Transition not working Java Android - java

I'm trying to implement a shared element transition between a fragment that has a Recyclerview and another fragment let say something like a Detail Fragment.
The fragments are:
<fragment
android:id="#+id/nav_staff"
android:name="main.staff.StaffFragment"
android:label="#string/menu_staff"
tools:layout="#layout/fragment_staff">
<action
android:id="#+id/action_nav_staff_to_nav_user_profile"
app:destination="#id/nav_user_profile">
<argument
android:name="selectedUser"
app:argType="string" />
</action>
</fragment>
<fragment
android:id="#+id/nav_user_profile"
android:name="main.staff.UserProfileFragment"
android:label="#string/profile"
tools:layout="#layout/fragment_user_profile" />
In the recycler view adapter I'm setting the element transition name like:
public void setBinding(UserModel model, OnItemClicked onUserClick) {
binding.setModel(model);
binding.executePendingBindings();
binding.coworkerImage.setTransitionName(model.getUid());
binding.itemContainer.setOnClickListener(v -> onUserClick.onItemClick(binding.coworkerImage, model.getUid()));
}
Then in the detail fragment in the onCreate method I'm setting:
setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));
then in the onViewCreated method of the detail fragment I'm setting the transition name of the image like:
userViewModel.getCurrentUser(selectedUid).observe(getViewLifecycleOwner(), model -> {
USER = model;
binding.userAvatar.setTransitionName(USER.getUid());
binding.setModel(USER);
});
In the main fragment when I click an item of the recycler view the transition animation is not happening, I did everything according to the documentation:
private void onItemClick(View v, String uid) {
FragmentNavigator.Extras extras = new FragmentNavigator.Extras.Builder()
.addSharedElement(v, v.getTransitionName())
.build();
StaffFragmentDirections.ActionNavStaffToNavUserProfile action =
StaffFragmentDirections.actionNavStaffToNavUserProfile(uid);
navController.navigate(action, extras);
}
The idea is: when I click an item in the recycler view it should open the detail fragment with shared element transition.

Related

How to return from activity to a specific fragment in navigation bottom

hello guys,
I'm developing an android app in which I need your help.
in this app, I have a bottom nav bar so I can communicate between 4 fragments A, B, C, and D.
I put the A fragment as the default home fragment.
the problem that, if I want to start my navigationBottom activity (A is the default home fragment after LogInstrong text)
I want to start it with a fragment C for example.
<navigation 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/nav"
app:startDestination="#id/account">
Welcome to Stackoverflow :)
Solution
Add these lines in your First Activity(From which you are moving to BottomNav Class)
`Intent intent = new Intent(YourActivity.this, BottomNavAvtivity.class);
intent.putExtra("FromMainActivity", "1");
startActivity(intent);`
Next,In your Second Activity(Class implementing BottomNav) write the below code in onCreate() of BottomNavigation class:
Intent i = getIntent();
String data = i.getStringExtra("FromReservation");
if (data != null && data.contentEquals("1")) {
yourBottomNav.setFragment(yourFragment);
}
This can be achieved with conditional navigation, I would recommend this medium article: https://medium.com/androiddevelopers/navigation-conditional-navigation-e82d7e4905f0
Especially the section around this code snippet (copy-pasted from the medium article) which shows how to change the default screen depending on a shared preferences value:
donutListViewModel.isFirstRun().observe(viewLifecycleOwner) { s ->
if (s == UserPreferencesRepository.Selection.NOT_SELECTED) {
val navController = findNavController()
navController.navigate(
DonutListDirections.actionDonutListToSelectionFragment()
)
}
}

App crashes when trying to open activity inside recyclerview that's inside a fragment [duplicate]

This question already has answers here:
java.lang.IllegalStateException: ScrollView can host only one direct child [duplicate]
(1 answer)
Scrollview can host only one direct child [duplicate]
(1 answer)
Closed 4 years ago.
I have a fragment that contains a recyclerview where I add an onclick listener to each item inside the Adapter like below
public void onBindViewHolder(CardViewHolder holder, int position) {
// Get the current news item at the position
final News currentItem = mNewsList.get(position);
// Get the news title information from the current news item and
// set text on the news title {#link TextView}
holder.newsTitleTextView.setText(currentItem.getTitle());
// Get the news section information from the current news item
// and set text on the section {#link TextView}
holder.sectionNameTextView.setText(currentItem.getSection());
// Get the published date of the current news item information from the current news item
// and set the same as text on the date published {#link TextView}
holder.datePublishedTextView.setText(currentItem.getTestDate());
// Register and setup listener to open up news story in web browser
holder.storyCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Parse string as url object
//Uri webpage = Uri.parse(currentItem.getStoryUrl());
Intent i = new Intent(v.getContext().getApplicationContext(), NewsReader.class);
i.putExtra("image", currentItem.getThumbnail());
i.putExtra("title", currentItem.getTitle());
i.putExtra("body", currentItem.getSection());
i.putExtra("date", currentItem.getTestDate());
i.putExtra("url", currentItem.getStoryUrl());
v.getContext().getApplicationContext().startActivity(i);
}
});
// Check whether or not the current news item has a thumbnail or not
if (currentItem.getThumbnail() == null) {
// The current news item does not have thumbnail information
// Set scale type for the default image
holder.newsThumbnail.setScaleType(ImageView.ScaleType.CENTER);
// Set the default image on the {#link ImageView} for the thumbnail
holder.newsThumbnail.setImageResource(R.drawable.no_thumbnail);
} else {
// The current news item has thumbnail information
holder.newsThumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
// Get the bitmap thumbnail from the current news item and
// Set it as the image on the {#link ImageView} thumbnail
holder.newsThumbnail.setImageBitmap(currentItem.getThumbnail());
}
}
I'm getting the following runtime error everytime I click on one of the recyclerview items:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.thenews/com.example.android.thenews.NewsReader}: android.view.InflateException: Binary XML file line #0: ScrollView can host only one direct child
<ScrollView .....>
//if you want to add some layout it has to have one body so you need to place in one body like this
<LinearLayout..>
<...Some Layouts .../>
</LinearLayout>
</ScrollView>
In Your Xml file, there must be Two Viewgroup inside your Scrollview.
As your error suggests.
ScrollView can host only one direct child
You have to make one Main Layout Inside your xml file and encapsulate them with Scrollview. just like this
<Scrollview>
<LinearLayout>
//your content
</LinearLayout>
</Scrollview>

What is the recommended way to launch a DialogFragment from a ViewModel?

I have a list objects in a Recyclerview. When long-pressing an item I want to show a dialog with data from the item clicked.
The Recyclerview is using data binding for each item and I am able to display data from the selected item using Log when long-pressing.
When trying to show a dialog, however, you need to get to the Activity, which is not recommended to use in the ViewModel object.
So how can I show the dialog?
Thanks, Ove
Conceptually a ViewModel strikes me as the wrong place to launch a Dialog from. To do it more cleanly I would pass the RecyclerView.ViewHolder into the layout, and have a method on the ViewHolder that triggers a custom listener on your RecyclerView.Adapter. Then whoever subscribes to that listener (Activity/Fragment) can launch the Dialog. May seem a little roundabout, but I don't think a ViewModel of a list item should have knowledge or control of its environment.
Here is an example. This is a general pattern for handling RecyclerView item clicks with data binding and a ViewModel. This is not a complete example, just the code to highlight this specific pattern.
Layout:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<data>
<variable
name="viewHolder"
type="com.example.ViewHolder"
/>
<variable
name="viewModel"
type="com.example.ViewModel"
/>
</data>
<com.example.View
android:layout_width="match_parent"
android:layout_height="24dp"
android:onClick="#{() -> viewHolder.onClick(viewModel)}"
/>
</layout>
Adapter:
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public interface SelectionListener {
void onSelectionChanged(int newPosition, ViewModel viewModel);
}
private #NonNull WeakReference<SelectionListener> selectionListener =
new WeakReference<>(null);
public void setSelectionListener(#Nullable SelectionListener listener) {
selectionListener = new WeakReference<>(listener);
}
public class ViewHolder extends RecyclerView.ViewHolder<ViewBinding> {
ViewHolder(ViewBinding binding) {
super(binding.getRoot());
binding.setViewHolder(this);
binding.setViewModel(new ViewModel());
}
public void onClick(ViewModel viewModel) {
SelectionListener listener = selectionListener.get();
if (listener != null) {
listener.onSelectionChanged(getAdapterPosition(), viewModel);
}
}
}
}
See the Variables section of the official documentation of the Data Binding Library. There you find a variable context you can use.
A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.
Basically you could just pass it to another variable like the viewModel to show the dialog from there.
android:onClick="#{v -> viewModel.showDialog(context)}"
I think using a binding adapter for a recyclerview and put the adapter n ViewModel, then make the viewmodel is the model of fragment and passing adapter for the setAdapter method in xml itself.
So you can use the context of item for example itemView.getContext() to show AlertDialog
The hint from Bayoudh led me in the right direction, but I'm posting this to put the pieces together. Below is a cardview that is clickable. Since my ViewModel holds no reference to the activity we have to pass the view in question as a parameter.
<android.support.v7.widget.CardView
android:id="#+id/cardviewContact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/text_margin_0.5x"
android:layout_marginRight="#dimen/text_margin_0.5x"
android:layout_marginTop="#dimen/text_margin_0.5x"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:minHeight="50dp"
card_view:cardCornerRadius="4dp"
android:onClick="#{(view) -> viewModel.onClick(view)}" >
The android:onClick="#{(view) -> viewModel.onClick(view)}" statement takes the current view as a parameter so you can use it in the ViewModel to get context with view.getContext() as Bayoudh states.

How to change style of specific rows in android ListView

I have a listview in my app, which is declared in XML, then the content is passed to it in code based on a string array which I have declared in XML. I'm new to android programming, but I was wondering how I could make the text in certain listview elements bold and darken the listview background behind it.
I have my set names as an array in my strings.xml:
<string-array name="setsArray">
<item>set1</item>
<item>set2</item>
<item>set3</item>
<item>set4</item>
<item>set5</item>
<item>set6</item>
</string-array>
I have my listview declared in the activity's layout.xml
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/app_bar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
And in the code of the activity I have this:
final ListView setList = (ListView) findViewById(R.id.listView);
setList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.setsArray)));
setList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
String itemValue = (String) setList.getItemAtPosition(itemPosition);
if (!itemValue.equals("SPANISH")){
Intent intent = new Intent(view.getContext(), SetViewActivity.class);
intent.putExtra("value", itemValue);
startActivity(intent);
}
}
});
Note that this code takes the name of the set that was clicked on, and passes it onto the next activity with the intent so it knows what to display. If possible I need to keep this intact or replace it with another system which sends something which I can use to distinguish the sets in the next activity.
because you don't use a custom adapter (I guess), try this please:
<string-array name="setsArray">
<item>set1</item>
<item>set2</item>
<item>set3</item>
<item>set4</item>
<item> <![CDATA[ <b>set5</b> ]]> </item>
<item>set6</item>
</string-array>
I hope android using Html.fromHtml() by default :)
Android:Make characters bold in xml
Please watch The World of ListView. It explains the important aspects of ListViews and how to make an adapters for your ListView. Pay particular attention to the part about using getItemViewType() and getViewTypeCount().
I think you'll have to implement custom ListAdapter. In getView() method you'll be able to change style of item based on index.
As a side note, I don't see a reason why you wouldn't use RecyclerView. It's a more flexible and up to date choice for creating lists.
With RecyclerView it could be done like this:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position]);
if(position == 5) holder.mTextView.setTypeface(null, Typeface.BOLD);
}

How do I clear ListView selection?

TL;DR: You choose an option from (a) my listview. Then, you change your mind and type something in (b) my edit text. How do I clear your listview selection and only show your edittext? (and vice versa)
I have an application with a listview of options as well as an edittext to create an own option. I need the user to either choose or create an option, but not both. Here's a drawing of my layout:
Whenever the user selects an option from the listview, I set it as "selected" by making it green, like so:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#color/colorPrimary"/>
<item
android:state_selected="false"
android:drawable="#color/windowBackground" />
</selector>
(this is set as the background of my listview)
Problem: I want to unselect the listview option if the user decides to type in their own option since they can only have one option.
User selects an option from the listview
User decides they want to create their own option using the edittext
The listview option is unselected when they start typing their own
I've tried doing the following, but nothing unselects.
e.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
for(int i=0; i<=5; i++){
listView.setItemChecked(i, false);
}
listView.clearChoices();
listView.requestLayout()
adapter.notifyDataSetChanged()
}
}
A very puzzling predicament, any help is appreciated!
Edit: here is the layout of the edittext:
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView4"
android:layout_alignBottom="#+id/textView4"
android:layout_toEndOf="#+id/textView4"
android:layout_toRightOf="#+id/textView4"
android:color="#color/colorPrimary"
android:imeOptions="actionDone"
android:inputType="text"
android:textColor="#color/textColorPrimary"
android:textColorHint="#color/colorPrimary" />
Edit: here is the layout of the listview:
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/toolbar"
android:background="#drawable/bg_key"
android:choiceMode="singleChoice"
android:listSelector="#color/colorPrimary">
</ListView>
Long Story Short
ListView selector (android:listSelector) is designed to indicate a click event, but not selected items.
If a ListView selector is drawn (after first click) it won't dissapear without drastic changes in the ListView
Hence use only drawables with transparent background if no state is applied to it as a ListView selector. Don't use a plain color resource for it, don't confuse yourself.
Use ListView choice mode (android:choiceMode) to indicate selected items.
ListView tells which row is selected by setting android:state_activated on the row's root view. Provide your adapter with corresponding layout/views to represent selected items correctly.
TL/DR Solutions
You can hide/remove selector with one of the following:
Making the selector transparent getSelector().setAlpha(0)
Resetting the current adapter with setAdapter(myAdapter) (adapter might be the same)
Solutions that might or might not work, depending on the OS version:
Making the list view to refresh layout completely via requestLayout(), invalidate() or forceLayout() methods;
Making the list view to refresh layout via notifyDataSetChanged()
Theory
Well, the built-in selection in ListView is utterly tricky at a first glance. However there are two main distinctions you should keep in mind to avoid confusing like this - list view selector and choice mode.
ListView selector
ListView selector is a drawable resource that is assumed to indicate an event of clicking a list item. You can specify it either by XML-property android:listSelector or using method setSelector(). I couldn't find it in docs, but my understanding is that this resource should not be a plain color, because after it's being drawn, it won't vanish without drastic changes in the view (like setting an adapter, that in turn may cause some glitches to appear), hence such drawable should be visible only while particular state (e.g. android:state_pressed) is applied. Here is a simple example of the drawable that can be used as a List View selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#android:color/darker_gray" />
<item
android:drawable="#android:color/transparent" />
</selector>
For whatever reason you cannot use a Color State List as List View selector, but still can use plain colors (that are mostly inappropriate) and State List drawables. It makes things somewhat confusing.
After the first click on a List View happens, you will not be able to remove List View selector from the List View easily.
The main idea here is that List View selector is not designed to indicate selected item.
ListView choice mode
ListView choice mode is assumed to indicate selected items. As you might know, primarily there are two choice modes we can use in ListView - Single Choice and Multiple Choice. They allow to track a single or multiple rows selected respectively. You can set them via android:choiceMode XML-property or setChoiceMode() method.
The ListView itself keeps selected rows in it and let them know which one is selected at any given moment by setting android:state_activated property of the row root view. In order to make your rows reflect this state, their root view must have a corresponding drawable set, e.g. as a background. Here is an example of such drawable:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_activated="true"
android:drawable="#android:color/holo_green_light" />
<item
android:drawable="#android:color/transparent" />
</selector>
You can make rows selected/deselected programmatically using the setItemChecked() method. If you want a ListView to clear all selected items, you can use the clearChoices() method. You also can check selected items using the family of the methods: getCheckedItemCount(), getCheckedItemIds(), getCheckedItemPosition() (for single choice mode), getCheckedItemPositions() (for multiple choice mode)
Conclusion
If you want to keep things simple, do not use the List View selector to indicate selected items.
Solving the issue
Option 1. Dirty fix - hide selector
Instead of actually removing selector, changing layouts and implementing a robust approach, we can hide the selector drawable when it's needed and show it later when clicking a ListView item:
public void hideListViewSelector() {
mListView.getSelector().setAlpha(0);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mListView.getSelector().getAlpha() == 0) {
mListView.getSelector().setAlpha(255);
}
}
Option 2. Thoughtful way
Let's go through your code and make it comply the rules i described step by step.
Fix ListView layout
In your ListView layout the selector is set to a plain color, and therefore your items are colored by it when they are clicked. The drawable you use as the ListView background have no impact, because ListView state doesn't change when its rows are clicked, hence your ListView always has just #color/windowBackground background.
To solve your problem you need at first remove the selector from the ListView layout:
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/toolbar"
android:listSelector="#color/colorPrimary"
android:background="#color/windowBackground"
android:choiceMode="singleChoice"/>
Make your rows reflect activated state
In the comments you give your adapter as follows:
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, text1, listOfThings);
You also asked me if it's possible to keep using standard adapter to achieve desired behavior. We can for sure, but anyway a few changes are required. I can see 3 options for this case:
1. Using standard android checked layout
You can just specify a corresponding standard layout - either any of the layouts that use CheckedTextView without changed background drawable as the root component or of those that use activatedBackgroundIndicator as their background drawable. For your case the most appropriate option should be the simple_list_item_activated_1. Just set it as in your ArrayAdapter constructor like this:
final ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_activated_1, android.R.id.text1, listOfThings);
This option is the closest to what i understand by 'standard' adapter.
2. Customize your adapter
You can use standard layout and mostly standard adapter with a small exception of getting a view for your items. Just introduce an anonymous class and override the method getView(), providing row views with corresponding background drawable:
final ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, listOfThings) {
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final View view = super.getView(position, convertView, parent);
if (convertView == null) {
view.setBackgroundResource(R.drawable.list_item_bg);
}
return view;
}
};
3. Customize your layout
The most common way of addressing this issue is of course introducing your own layout for the items view. Here is my simple example:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/list_item_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="16dp">
<TextView
android:id="#android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
I saved it in a file /res/layout/list_view_item.xml Do not forget setting this layout in your adapter:
final ArrayAdapter<String> adapter = new ArrayAdapter(this, R.layout.list_view_item, android.R.id.text1, listOfThings);
Clearing selection
After that your rows will reflect selected state when they are clicked, and you can easily clear the selected state of your ListView by calling clearChoices() and consequence requestLayout() to ask the ListView to redraw itself.
One little comment here that if you want unselect the item when user start typing, but not when he actually clicks the return (done) button, you need to use a TextWatcher callback instead:
mEditText.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) {
if (mListView.getCheckedItemCount() > 0) {
mListView.clearChoices();
mListView.requestLayout();
}
}
#Override
public void afterTextChanged(Editable s) {}
});
Hopefully, it helped.
I have a good solution to do that. Add EditText to your layout which contains on your ListView as this layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:choiceMode="singleChoice"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Comment"
android:layout_below="#id/list_view"
android:id="#+id/editText"
android:nextFocusUp="#id/editText"
android:nextFocusLeft="#id/editText"/>
</RelativeLayout>
Then initialize Boolean variable to check whether editText if focused or not for example use this : boolean canBeSelected = true;
Then after setting adapter use this code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (canBeSelected) {
listView.setSelector(R.drawable.background);
listView.setSelected(true);
listView.setSelection(i);
} else {
if (!editText.isFocused()){
canBeSelected = true;
listView.setSelector(R.drawable.background);
listView.setSelected(true);
listView.setSelection(i);
}
}
}
});
editText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
canBeSelected = false;
Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);
listView.setSelector(transparentDrawable);
listView.clearChoices();
listView.setSelected(false);
return false;
}
});
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (editText.isFocused()){
Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);
listView.setSelector(transparentDrawable);
listView.clearChoices();
listView.setSelected(false);
canBeSelected = false;
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);
listView.setSelector(transparentDrawable);
listView.clearChoices();
listView.setSelected(false);
canBeSelected = false;
}
#Override
public void afterTextChanged(Editable editable) {
if (editText.isFocused()) {
Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);
listView.setSelector(transparentDrawable);
listView.clearChoices();
listView.setSelected(false);
canBeSelected = false;
}
}
});
}
Hope it works with you :)
Re-setting the adapter in the edittext listener worked for me:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
listview.clearChoices();
listview.setAdapter(adapter);
Toast.makeText(getApplicationContext(),"Typing" + listview.getSelectedItemPosition(), Toast.LENGTH_SHORT).show();
}
#Override
public void afterTextChanged(Editable editable) {
}
});
I put the selected index in a toast to check if the item was correctly deselected.
Hope this works!!
Just call clear when you make the request for the second data set:
arrayAdapter!!.clear()
You load your first data set
The user select one elements,
This action highlight your item
For any reason you launch the reload of your data set (because edittext's value changed),
at this moment call, clear() on your adapter.
Then you retrieved your dataset, you send it to the arrayAdapter and
No one is selected .
This is because when you clear, it also clear the selected flag

Categories

Resources