Here is a function that gets called when an item gets selected from a ListView:
async void detail_clicked(object sender, SelectedItemChangedEventArgs e){
if (e.SelectedItem == null) {
return;
}
Detail selected = (Detail)e.SelectedItem;
order_vm.List_of_details.Add(selected);
await DisplayAlert ("Item Added",
String.Format ("{0} added to cart.", selected.detail_name), "Okay");
((ListView)sender).SelectedItem = null;
}
I added this function using the ItemSelected event handler
details_list.ItemSelected += detail_clicked;
The first time I click on the Item, the DisplayAlert pops up. After the first click, the DisplayAlert inside detail_clicked no longer pops up. But the other code inside the handler does get called.
Anyone know how to fix this issue? Is it something I am not understanding about event handlers? Is it something about await/async?
The DisplayAlert might be running on a different thread. Try wrapping Display Alert in Device.BeginInvokeOnMainThread. You can ready about that here.
Please check again without async on method and await on DisplayAlert().
Use this following code. It will helps you.
private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
{
return;
}
listView.SelectedItem = null;
DisplayAlert("Alert", e.SelectedItem.ToString(), "Ok");
}
Related
How can I detect if the user creating a screenshot?
I do not care about the capture pictures, I just want to know when and where user creating the screenshot
How can I detect this in the flutter app?
You can try this plugin, it might be what you are looking for: https://pub.dev/packages/screenshot_callback
In order to accomplish what you are looking for from the README:
import 'package:screenshot_callback/screenshot_callback.dart';
ScreenshotCallback screenshotCallback = ScreenshotCallback();
screenshotCallback.addListener(() {
//Void funtions are implemented
print('detect screenshot');
});
try
https://pub.dev/packages/screenshot_callback
dependencies:
screenshot_callback: ^1.1.3
void init() async {
await initScreenshotCallback();
}
//It must be created after permission is granted.
Future<void> initScreenshotCallback() async {
screenshotCallback = ScreenshotCallback();
screenshotCallback.addListener(() {
setState(() {
text = "Screenshot callback Fired!";
});
});
screenshotCallback.addListener(() {
print("We can add multiple listeners ");
});
}
I'm trying to create a listener for the clear button that comes from google's Place Autocomplete API. i called my clearButton() method in my fragment's onViewCreated method
clearButton()
placeAutocompleteFragment?.view?.findViewById<View>(R.id.place_autocomplete_clear_button)
?.setOnClickListener {
View.OnClickListener {
Log.d(TAG, "Cleared")
it?.findViewById<EditText>(R.id.place_autocomplete_search_input)?.setText("")
it?.visibility = View.GONE
}
}
now when i click on the clear button icon, the text doesn't get erased, nothing happens. I can still type in a new location though, but i can't clear it. my Log.d isn't getting displayed either.
I don't have android studio on this machine now to try, but I guess you can do something like
place_autocomplete_clear_button.onClick { place_autocomplete_search_input.text = "" }
where place_autocomplete_clear_button can be static import and onClick might be from anko
Figured it out. I had the method calls set up all wrong.
Here's how it should look like:
private fun clearButton() {
placeAutocompleteFragment?.view?.findViewById<View>(R.id.place_autocomplete_clear_button)?.setOnClickListener {
Log.d(TAG, "Cleared Button Clicked")
it.visibility = View.GONE
//do something
}
}
I am using MvvmCross 4.2.3 and I have a query about when it is safe to call ShowViewModel
I am trying to call ShowViewModel to navigate in the Start method of ViewModelA to navigate to ViewModelB, however I get the following exception
Java.Lang.IllegalStateException: Recursive entry to executePendingTransactions
I assumed I was doing it too early in the lifecycle of ViewA\ViewModelA. So I put the call into the OnResume of ViewA. I assumed at this point any transactions required to show ViewA would have been commited.
But I still get the same error.
Has anyone come accross this problem. If so how do I solve it.
Thanks in Advance
I am not being specific here , just trying to solve what you asked .
I think there could be two scenario .
scenerio first .
you want to navigate on user interaction lets say tapping on a button .
Inside view you can put this code in OnCreate or ViewModelSet method overrides .
var set = this.CreateBindingSet<MyView, MyViewModel>();
set.Bind(MyButton).For(zz => zz.BindClick()).To(vm => vm.MyCommand);
Inside your viewmodel, you would need this .
private ICommand myCommand;
public virtual ICommand MyCommand
{
get
{
return myCommand = myCommand ?? new MvxCommand(() => {
Task.Factory.StartNew(() => {
ShowViewModel<MyNextViewModel>();
});
});
}
}
Scenario 2 ,
You have some Async task going on based on completion of that you want to navigate .
Inside your viewmodel constructor you call a method like below .
Public MyViewModel(){
LoadActivation()
}
private async void LoadActivation()
{
await Task.Run(async () =>
{
try {
response = await _Myservice.LoadMyData();
if(response != null ) {
ShowViewModel<MyNextViewModel>():
}
}
catch (Exception ex) {
Debug.WriteLine(ex);
}
});
}
I am getting data (List) from an API and I am trying to update my AutcompleteTextView with this data.
This is how I currently do :
I have a TextWatcher which calls a the method to get the data in afterTextChanged, so every time the user stops typing the method is called, and the adapter is notified with ``notifyDataSetChanged :
//in onCreate
addressAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,suggestions_address);
at_address.setAdapter(addressAdapter);
...
#Override
public void afterTextChanged(Editable s) {
autoComplete(s);
addressAdapter.notifyDataSetChanged();
//suggestions_address is the updated list, and when I print it I can see the
//results so it is not empty
Log.i("addresses",suggestions_address.toString());
}
...
class SuggestionQueryListener implements ResultListener<List<String>> {
#Override
public void onCompleted(List<String> data, ErrorCode error) {
if (error != ErrorCode.NONE) {
Toast.makeText(MainActivity2.this,error.toString(),Toast.LENGTH_LONG).show();
} else {
suggestions_address.clear();
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
}
}
}
public void autoComplete(CharSequence s) {
try {
String term = s.toString();
TextSuggestionRequest request = null;
request = new TextSuggestionRequest(term).setSearchCenter(new GeoCoordinate(48.844900, 2.395658));
request.execute(new SuggestionQueryListener());
if (request.execute(new SuggestionQueryListener()) != ErrorCode.NONE) {
//Handle request error
//...
}
} catch (IllegalArgumentException ex) {
//
}
}
But it seems that the adapter is not really updated because it doesn't show the suggestions when I type something.
Also, before doing this with an AutoCompleteTextView I did it with a listView, with the same process, and everything worked well.
Any ideas or solutions would be really appreciated
EDIT : I noticed something really strange : the data is not binded to the adapter, because adapter#getCount always returns 0, even if the list is not empty. But when I remove at_address.setAdapter(addressAdapter), the data adapter is updated and adapter#getCount returns the right number of elements.
I am really confused right now, please help !
Instead of this:
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
you can use just this:
suggestions_address.addAll(data);
you are calling notifyDataSetChanged after you start the request, you should call it after you get the result and update the suggestions_address, so call notifyDataSetChanged inside onCompleted
I'm developing a codebar app for android with Xamarin and the Zxing library.
My objective was to have in the same view half of the screen with the codebar view, and the other half with the buttons to add or delete the scanned object to a list.
In MainActivity OnCreate function I have:
scanFragment = new ZXingScannerFragment();
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
fragmentTx.Replace(Resource.Id.fragment, scanFragment);
fragmentTx.SetTransition(FragmentTransit.FragmentFade);
fragmentTx.Commit();
In ZXingScannerFragment OnCreate I have
frame = (FrameLayout)layoutInflater.Inflate(Resource.Layout.zxingscannerfragmentlayout, viewGroup, false);
return frame;
What I want it that, when the user scans something the view of the camera shut off, and then when the user has decided if wants to keep or discard the scanned object the camera shows again.
So I have a scann function called when the code is detected on MainActivity, who calls the OnPause method in the Zxing fragment and enables the buttons with this code:
var opts = new MobileBarcodeScanningOptions {
PossibleFormats = new List<ZXing.BarcodeFormat> {
ZXing.BarcodeFormat.All_1D,
}
};
scanFragment.StartScanning(result => {
if (result == null || string.IsNullOrEmpty(result.Text)) {
Toast.MakeText(this, "Scanning Cancelled", ToastLength.Long).Show();
return;
}
else
{
_player.Start();
RunOnUiThread(() => codBox.Text = result.Text);
RunOnUiThread(() => addBut.Enabled = true);
RunOnUiThread(() => delBut.Enabled = true);
RunOnUiThread(() => masBut.Enabled = true);
RunOnUiThread(() => menBut.Enabled = true);
RunOnUiThread(() => buttonDate.Enabled = true);
RunOnUiThread(() => finishBut.Enabled = false);
scanFragment.OnPause();
}
}, opts);
And then I have another function who calls the OnResume from Zxing fragment.
The OnPause function looks like:
base.OnPause ();
if (scanner != null)
{
frame.RemoveView(scanner);
if (!UseCustomOverlayView)
frame.RemoveView(zxingOverlay);
else if (CustomOverlayView != null)
frame.RemoveView(CustomOverlayView);
scanner.ShutdownCamera();
scanner = null;
}
The problem is:
With this code the OnPause function gives a "Only the original thread that created a view hierarchy can touch its views" Exception, but if I ignore it all works well some random time. I can take a code, camera vanishes, then add or remove object, and call camera again and all works fine 5... 10... 15 times in a row until I get a "Unhandled Exception: Java.Lang.NullPointerException" with no Idea were is being fired and no more info.
If I do something to prevent the hierarchy exception like:
if (scanner != null)
{
var myActivity = (MainActivity)this.Activity;
myActivity.RunOnUiThread(() =>
{
frame.RemoveView(scanner);
if (!UseCustomOverlayView)
frame.RemoveView(zxingOverlay);
else if (CustomOverlayView != null)
frame.RemoveView(CustomOverlayView);
});
scanner.ShutdownCamera();
scanner = null;
}
The camera vanishes, no exception is throwed but when I call the OnResume I get a static image of the last code detected.
At the end after many attempts I realized I was using a unmanaged crash as a correct behaviour of my app.
What I do is instead of calling the OnResume and OnPause functions (who have clearly objectives) of the Zxingfragment call directly scan function and stopscanning function.