instant Search functionality to listview using edittext in xamarin android - c#

I am trying to implement instant search functionality using edittext.I have just binded the json array response to listview and added edittext at top of listview and trying to filter or search data in listview as user starts to type in edittext below code is used.Please help me. Any kind of suggestion,guidence and help is appreciated.
MainActivity.cs
SetContentView(Resource.Layout.HomeScreen);
tableItems = new List<TableItem>();
var client = new RestClient("http://azurewebsites.net/");
var request = new RestRequest("Service/regionSearch", Method.POST);
request.RequestFormat = DataFormat.Json;
tableItems = client.Execute<List<TableItem>>(request).Data;
listView.Adapter = new HomeScreenAdapter(this, tableItems);
region = FindViewById<TextView> (Resource.Id.viewtext);
area= FindViewById<TextView> (Resource.Id.viewtext2);
_filterText = FindViewById<EditText>(Resource.Id.search);
listView = FindViewById<ListView>(Resource.Id.listView);
_filterText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
// filter on text changed
var searchTerm = _filterText.Text;
};
listView.ItemClick += OnListItemClick;
}
protected void OnListItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e)
{
var listView = sender as ListView;
var t = tableItems[e.Position];
// var clickedTableItem = listView.Adapter[e.Position];
Android.Widget.Toast.MakeText(this, clickedTableItem.DDLValue, Android.Widget.ToastLength.Short).Show();
}
HomeScreenAdapter.cs
public class HomeScreenAdapter : BaseAdapter<TableItem> {
List<TableItem> items;
Activity context;
public HomeScreenAdapter(Activity context, List<TableItem> items)
: base()
{
this.context = context;
this.items = items;
}
public override long GetItemId(int position)
{
return position;
}
public override TableItem this[int position]
{
get { return items[position]; }
}
public override int Count
{
get { return items.Count; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = items[position];
// TableItem item = items[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.CustomView, null);
view.FindViewById<TextView>(Resource.Id.Text1).Text = item.DDLValue;
view.FindViewById<TextView>(Resource.Id.Text2).Text = item.areaMsg;
return view;
}
}

It looks like you're pretty close. The last step is to use the searchTerm to filter out the results in tableItems. The easiest way to do this is to simply create a new HomeScreenAdapter with the filtered list, and set that as the ListView.Adapter. Check out this example code that implements: getting the search text, filtering all of your TableItem instances, and then giving the ListView a new Adapter.
_filterText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
// filter on text changed
var searchTerm = _filterText.Text;
var updatedTableItems = tableItems.Where(
// TODO Fill in your search, for example:
tableItem => tableItem.Msg.Contains(searchTerm) ||
tableItem.DDLValue.Contains(searchTerm)
).ToList();
var filteredResultsAdapter = new HomeScreenAdapter(this, updatedTableItems);
listView.Adapter = filteredResultsAdapter;
};
Notice the TODO inside of the Where clause. I have no idea how you want to search on your TableItem but once you write your Where clause, this should do what you want.
It looks like your TableItem class is something like this (for reference):
public class TableItem {
public int Id {get; set;}
public string DDLValue {get; set;}
public string Msg {get; set;}
public int Status {get; set;}
}

Related

retrieve image path from sqlite in image adapter (GridView on Xamarin Android C#)

I want to display my picture in the gridview. The picture is coming from the path and the path is stored in the SQLite database. I try the tutorial from MSDN here https://learn.microsoft.com/en-us/xamarin/android/user-interface/layouts/grid-view and I modified and changed my resource.drawable.image into the image path (the image path is from the database), but I don't know how to do that. I try using the bitmap method but I still confused about how I can make it array using this method. I want to get the picture data such as photo title, photo description, and photo path from the database and store it into my List<> or array.
I already make the database and try to call it but, I still confused. Please help me.
So, this is an object class for the table. It called Photo.cs
[Table("tblPhoto")]
public class Photo
{
[PrimaryKey, AutoIncrement, Column("pkPhotoID")]
public int PhotoID { get; set; }
[Column("fkUserID")]
public int UserID { get; set; }
public string PhotoPath { get; set; }
public string PhotoName { get; set; }
public string PhotoDescription { get; set; }
private DateTime _creationDate;
public string CreationDate
{
get { return _creationDate.ToString(); }
set { _creationDate = DateTime.ParseExact(value, "yyyy:MM:dd HH:mm:ss", null); }
}
private DateTime _uploadDate;
public string UploadDate
{
get { return _uploadDate.ToString(); }
set { _uploadDate = DateTime.Parse(value); }
}
//show User Photo
public static Photo ShowUserPhoto()
{
return DBManager.Instance.Query<Photo>($"SELECT * FROM tblPhoto a JOIN tblUser b WHERE a.UserID== b.UserID").FirstOrDefault();
}
//show photo path and its photo
public static Photo ShowPhotoPath(string aPhotoPath)
{
return DBManager.Instance.Query<Photo>($"SELECT * FROM tblPhoto WHERE PhotoPath=='{aPhotoPath}'").FirstOrDefault();
}
//show all
public static Photo ShowAllPhoto()
{
return DBManager.Instance.Query<Photo>($"SELECT * FROM tblPhoto").FirstOrDefault();
}
and the second is for ImageAdapter because I want to display the picture in gridview. It called the ImageAdapter.cs
public class ImageAdapter : BaseAdapter
{
private Context context;
private List<string> gridViewString;
private List<string> gridViewImage;
public ImageAdapter(Context context, List<string> gridViewstr, List<string> gridViewImage)
{
this.context = context;
gridViewString = gridViewstr;
this.gridViewImage = gridViewImage;
}
public override int Count
{
get
{
return gridViewString.Count;
}
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return 0;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view;
LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
if (convertView == null)
{
view = new View(context);
view = inflater.Inflate(Resource.Layout.gridview_layout, null);
TextView txtview = view.FindViewById<TextView>(Resource.Id.textPhotoTitleViewGrid);
ImageView imgview = view.FindViewById<ImageView>(Resource.Id.imageViewGrid);
txtview.Text = gridViewString[position];
imgview.SetImageBitmap(GetImageBitmapFromDB(gridViewImage[position]));
}
else
{
view = (View)convertView;
}
return view;
}
private Android.Graphics.Bitmap GetImageBitmapFromDB(string aPath)
{
Android.Graphics.Bitmap imageBitmap = null;
var _getPath = Model.Photo.ShowPhotoPath(aPath);
{
var imgPath = _getPath.ShowPhotoPath(aPath);
if (imgPath != null && imgPath.Length > 0)
{
imageBitmap = Android.Graphics.BitmapFactory.DecodeFile(imgPath);
}
}
return imageBitmap;
}
}
and the last is a fragment class called Fragment_home.cs The image should be displayed here
public class Fragment_Home : Android.Support.V4.App.Fragment
{
List<string> m_gridviewstring = new List<string>();
List<string> m_imgview = new List<string>();
GridView m_gridview;
public override void OnCreate(Bundle aSavedInstanceState)
{
base.OnCreate(aSavedInstanceState);
}
public static Fragment_Home NewInstance()
{
var _frag1 = new Fragment_Home { Arguments = new Bundle() };
return _frag1;
}
public override View OnCreateView(LayoutInflater aInflater, ViewGroup aContainer, Bundle aSavedInstanceState)
{
var _ignored = base.OnCreateView(aInflater, aContainer, aSavedInstanceState);
//String stringData = Arguments.GetString("email");
View _view = aInflater.Inflate(Resource.Layout.FragmentHome, null);
//var gridview = _view.FindViewById<GridView>(Resource.Id.gridview);
//gridview.Adapter = new ImageAdapter(Context);
//gridview.ItemClick += Gridview_ItemClick;
//return _view;
var _retrievePic = Model.Photo.ShowAllPhoto();
//_retrievePic.PhotoPath;
ImageAdapter adapter = new ImageAdapter(Activity, m_gridviewstring, m_imgview);
m_gridview = _view.FindViewById<GridView>(Resource.Id.grid_view_image_text);
m_gridview.Adapter = adapter;
return _view;
}
}
Please help me, any help?
I post two images in /storage/emulated/0/DCIM/Camera/ path and "/storage/emulated/0/Pictures" path as well. For testing, I re-name Photo names.
Here is running gif(Please ignore the nest fragments, I do not want to create a new demo from start to end,I used my previous demo).
Firstly, I create a PhotoDAO.cs, it will insert data to DB and read all of data from DB. I have given a PhotoPath and PhotoName when insert data to DB.
public class PhotoDAO
{
static SQLiteConnection db;
public List<Photo> GetAllPhotos()
{
Console.WriteLine("Reading data");
var table = db.Table<Photo>();
List<Photo> photos = table.ToList<Photo>();
return photos;
}
public static void DoSomeDataAccess()
{
Console.WriteLine("Creating database, if it doesn't already exist");
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Photo1.db3");
db = new SQLiteConnection(dbPath);
db.CreateTable<Photo>();
if (db.Table<Photo>().Count() == 0)
{
// only insert the data if it doesn't already exist
var newPhoto1 = new Photo();
newPhoto1.UserID = 1;
newPhoto1.PhotoPath = "/storage/emulated/0/Pictures/";
newPhoto1.PhotoName = "icon.png";
newPhoto1.PhotoDescription = "This is a hamburger";
db.Insert(newPhoto1);
var newPhoto2 = new Photo();
newPhoto2.UserID = 2;
newPhoto2.PhotoPath = "/storage/emulated/0/Pictures/";
newPhoto2.PhotoName = "person.jpg";
newPhoto2.PhotoDescription = "This is a person";
db.Insert(newPhoto2);
var newPhoto3 = new Photo();
newPhoto3.UserID = 3;
newPhoto3.PhotoPath = "/storage/emulated/0/DCIM/Camera/";
newPhoto3.PhotoName = "IMG1.jpg";
newPhoto3.PhotoDescription = "This is a IMG1";
db.Insert(newPhoto3);
var newPhoto4 = new Photo();
newPhoto4.UserID = 4;
newPhoto4.PhotoPath = "/storage/emulated/0/DCIM/Camera/";
newPhoto4.PhotoName = "IMG2.jpg";
newPhoto4.PhotoDescription = "This is a IMG2";
db.Insert(newPhoto4);
}
}
}
Then in the Fragment_Gallery.cs, we set a Adapter for GridView. Here is code.
public class Fragment_Gallery : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment_Gallery NewInstance()
{
var frag1 = new Fragment_Gallery { Arguments = new Bundle() };
return frag1;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
View view = inflater.Inflate(Resource.Layout.galleryfragment, null);
var gridview = view.FindViewById<GridView>(Resource.Id.gridview);
PhotoDAO.DoSomeDataAccess();
var photoDAO=new PhotoDAO();
List<Photo> photos=photoDAO.GetAllPhotos();
gridview.Adapter = new MyAdapter(this, photos);
return view;
}
}
Here is code about my gridview Adapter. I create a CustomView for test if you need custom the item in gridview in the future. I set Imageview source from local path, please see GetView method.
internal class MyAdapter :BaseAdapter<Photo>
{
private Fragment_Gallery fragment_Gallery;
private List<Photo> photos;
public MyAdapter(Fragment_Gallery fragment_Gallery, List<Photo> photos)
{
this.fragment_Gallery = fragment_Gallery;
this.photos = photos;
}
public override Photo this[int position] => photos[position];
public override int Count => photos.Count;
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null) // no view to re-use, create new
view = fragment_Gallery.LayoutInflater.Inflate(Resource.Layout.CustomView, null);
view.FindViewById<TextView>(Resource.Id.custUserID).Text = photos[position].UserID.ToString();
view.FindViewById<TextView>(Resource.Id.custPhotoPath).Text = photos[position].PhotoPath;
view.FindViewById<TextView>(Resource.Id.custPhotoName).Text = photos[position].PhotoName;
view.FindViewById<TextView>(Resource.Id.custPhotoDescription).Text = photos[position].PhotoDescription;
string imgFile = photos[position].PhotoPath + photos[position].PhotoName;
Bitmap myBitmap = BitmapFactory.DecodeFile(imgFile);
view.FindViewById<ImageView>(Resource.Id.custImage).SetImageBitmap(myBitmap);
return view;
}
}
Here is layout about CustomView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="#+id/custImage" />
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="#+id/custUserID"
android:text="#string/abc_action_bar_home_description"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="#+id/custPhotoPath"
android:text="#string/abc_action_bar_home_description"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="#+id/custPhotoName"
android:text="#string/abc_action_bar_home_description"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:id="#+id/custPhotoDescription"
android:text="#string/abc_action_bar_home_description"
/>
</LinearLayout>
In the end, please do not forget to add android.permission.WRITE_EXTERNAL_STORAGE in your AndroidManifest.xml
Here is my demo, you can download it and make a test(Please add Images like my PersonDAO class or you can change the name of image in PersonDAO class).
https://drive.google.com/file/d/1ipw534Q0C4UxHva3Jiv5SoI0KycifpmI/view?usp=sharing
=====update=======
If you want to achieve the click event, you can use gridview.ItemClick += Gridview_ItemClick; to achieve it. If you got image position from the adapter is not found, please add a break point Photo photo = photos[e.Position]; in the Gridview_ItemClick, if you got the e.Position correctly.
public class Fragment_Gallery : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static Fragment_Gallery NewInstance()
{
var frag1 = new Fragment_Gallery { Arguments = new Bundle() };
return frag1;
}
List<Photo> photos;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
View view = inflater.Inflate(Resource.Layout.galleryfragment, null);
GridView gridview = view.FindViewById<GridView>(Resource.Id.gridview);
gridview.ItemClick += Gridview_ItemClick;
PhotoDAO.DoSomeDataAccess();
var photoDAO=new PhotoDAO();
photos=photoDAO.GetAllPhotos();
gridview.Adapter = new MyAdapter(this, photos);
return view;
}
private void Gridview_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
// throw new NotImplementedException();
Photo photo = photos[e.Position];
Intent intent= new Intent(Context, typeof(DetailActivity));
intent.PutExtra("PicName", photo.PhotoName);
intent.PutExtra("PicDes", photo.PhotoDescription);
StartActivity(intent);
}
}
In the DetailActivity, you can got the picture info by following code.
public class DetailActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Detaillayout);
TextView detailPhotoName = FindViewById<TextView>(Resource.Id.detailPhotoName);
TextView detailPhotoDescription = FindViewById<TextView>(Resource.Id.detailPhotoDescription);
Bundle extras =Intent.Extras;
detailPhotoName.Text = extras.GetString("PicName");
detailPhotoDescription.Text = extras.GetString("PicDes");
// Create your application here
}
}
You want to display the picture bigger in the fragment layout or the DetailActivity? In the fragment layout, just set bigger value for columnWidth=200dp in GridView and Open the CustomView.xml, set bigger value for android:layout_width="200dp" android:layout_height="200dp" in ImageView
Here is click running gif.

How to acces object inside CarouselView Xamarin.Forms

I have a Xamarin.Forms app that displays a ViewFlipper (https://github.com/TorbenK/ViewFlipper) inside a CarouselView.
I would like the ViewFlipper to flip back to the front when changing pages inside the carousel. But I can't seem to figure out how to access the ViewFlipper.
I have the following working code:
public class CarouselContent
{
public string FrontImg { get; set; }
public string BackImg { get; set; }
}
public class MainPage : ContentPage
{
public MainPage()
{
var pages = new ObservableCollection<CarouselContent>();
var page1 = new CarouselContent();
page1.FrontImg = "page1Front";
page1.BackImg = "page1Back";
var page2 = new CarouselContent();
page2.FrontImg = "page2Front";
page2.BackImg = "page2Back";
pages.Add(page1);
pages.Add(page2);
var carouselView = new Carousel(pages);
Content = carouselView;
}
}
public class Carousel : AbsoluteLayout
{
private DotButtonsLayout dotLayout;
private CarouselView carousel;
public Carousel(ObservableCollection<CarouselContent> pages)
{
carousel = new CarouselView();
var template = new DataTemplate(() =>
{
//create page
var absLayout = new AbsoluteLayout();
//create images for the flipper
var frontImg = new Image
{
Aspect = Aspect.AspectFit
};
frontImg.SetBinding(Image.SourceProperty, "FrontImg");
var backImg = new Image
{
Aspect = Aspect.AspectFit
};
backImg.SetBinding(Image.SourceProperty, "BackImg");
//create flipper
var flipper = new ViewFlipper.FormsPlugin.Abstractions.ViewFlipper();
flipper.FrontView = frontImg;
flipper.BackView = backImg;
//Add flipper to page
absLayout.Children.Add(flipper);
return absLayout;
});
carousel.ItemsSource = pages;
carousel.ItemTemplate = template;
Children.Add(carousel);
}
}
I tried adding the ViewFlipper to the CarouselContent but I couldn't get that to work. Any ideas?
EDIT:
I tried creating an AbsoluteLayout with bindable items and bind the items created in CarouselContent in the datatemplate of the CarouselView, but the line '(b as BindableAbsLayout).Children.Add((View)v);' in BindableAbsLayout is never called. What am I doing wrong?
class BindableAbsLayout : AbsoluteLayout
{
public static readonly BindableProperty ItemsProperty =
BindableProperty.Create(nameof(Items), typeof(ObservableCollection<View>), typeof(BindableAbsLayout), null,
propertyChanged: (b, o, n) =>
{
(n as ObservableCollection<View>).CollectionChanged += (coll, arg) =>
{
switch (arg.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var v in arg.NewItems)
(b as BindableAbsLayout).Children.Add((View)v);
break;
case NotifyCollectionChangedAction.Remove:
foreach (var v in arg.NewItems)
(b as BindableAbsLayout).Children.Remove((View)v);
break;
}
};
});
public ObservableCollection<View> Items
{
get { return (ObservableCollection<View>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
}
public class CarouselContent
{
private ViewFlipper.FormsPlugin.Abstractions.ViewFlipper _flipper;
private ObservableCollection<View> _items;
public ObservableCollection<View> Items
{
get { return _items; }
}
public CarouselContent(string frontImgStr, string backImgStr)
{
_items = new ObservableCollection<View>();
_flipper = new ViewFlipper.FormsPlugin.Abstractions.ViewFlipper();
var frontImg = new Image
{
Aspect = Aspect.AspectFit
};
frontImg.Source = frontImgStr;
var backImg = new Image
{
Aspect = Aspect.AspectFit
};
backImg.Source = backImgStr;
_flipper.FrontView = frontImg;
_flipper.BackView = backImg;
AbsoluteLayout.SetLayoutBounds(_flipper, new Rectangle(0.5, 0.05, 0.85, 0.85));
AbsoluteLayout.SetLayoutFlags(_flipper, AbsoluteLayoutFlags.All);
Items.Add(_flipper);
}
}
public class Carousel : AbsoluteLayout
{
private DotButtonsLayout dotLayout;
private CarouselView carousel;
public Carousel(ObservableCollection<CarouselContent> pages)
{
carousel = new CarouselView();
var template = new DataTemplate(() =>
{
var absLayout = new BindableAbsLayout();
absLayout.BackgroundColor = Color.FromHex("#68BDE4");
absLayout.SetBinding(BindableAbsLayout.ItemsProperty,"Items");
return absLayout;
});
carousel.ItemsSource = pages;
carousel.ItemTemplate = template;
Children.Add(carousel);
}
}
Not sure what the best practice is here, but you could try accessing it via the ItemSelected Event (which fires every time you change back and forth in the carouselview)
Wire it up
carousel.ItemSelected += carouselOnItemSelected;
Get your ViewFlipper
private void carouselOnItemSelected(object sender, SelectedItemChangedEventArgs selectedItemChangedEventArgs)
{
CarouselContent carouselContent = selectedItemChangedEventArgs.SelectedItem;
ViewFlipper viewFlipper = carouselContent.Children[0];
viewFlipper.FlipState = ViewFlipper.FrontView;
}

Implementing Xamarin Forms context actions

I am trying to implement context actions on my list in Xamarin Forms but can't get it to work.
I am not using XAML, but instead creating my layout in code.
I am trying to follow the steps in https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/interactivity/#Context_Actions and I want to push a new page when "Edit" is clicked.
I cleaned up my code and removed my feeble attempts to make things work.
So this is my custom list cell:
public class PickerListCell : TextCell
{
public PickerListCell ()
{
var moreAction = new MenuItem { Text = App.Translate ("Edit") };
moreAction.SetBinding (MenuItem.CommandParameterProperty, new Binding ("."));
moreAction.Clicked += async (sender, e) => {
var mi = ((MenuItem)sender);
var option = (PickerListPage.OptionListItem)mi.CommandParameter;
var recId = new Guid (option.Value);
// This is where I want to call a method declared in my page to be able to push a page to the Navigation stack
};
ContextActions.Add (moreAction);
}
}
And here is my model:
public class OptionListItem
{
public string Caption { get; set; }
public string Value { get; set; }
}
And this is the page:
public class PickerPage : ContentPage
{
ListView listView { get; set; }
public PickerPage (OptionListItem [] items)
{
listView = new ListView () ;
Content = new StackLayout {
Children = { listView }
};
var cell = new DataTemplate (typeof (PickerListCell));
cell.SetBinding (PickerListCell.TextProperty, "Caption");
cell.SetBinding (PickerListCell.CommandParameterProperty, "Value");
listView.ItemTemplate = cell;
listView.ItemsSource = items;
}
// This is the method I want to activate when the context action is called
void OnEditAction (object sender, EventArgs e)
{
var cell = (sender as Xamarin.Forms.MenuItem).BindingContext as PickerListCell;
await Navigation.PushAsync (new RecordEditPage (recId), true);
}
}
As you can see by my comments in the code, I have indicated where I believe things are missing.
Please assist guys!
Thanks!
Probably is too late for you, but can help others. The way i've found to do this is passing the instance of page on creation the ViewCell.
public class PickerListCell : TextCell
{
public PickerListCell (PickerPage myPage)
{
var moreAction = new MenuItem { Text = App.Translate ("Edit") };
moreAction.SetBinding (MenuItem.CommandParameterProperty, new Binding ("."));
moreAction.Clicked += async (sender, e) => {
var mi = ((MenuItem)sender);
var option = (PickerListPage.OptionListItem)mi.CommandParameter;
var recId = new Guid (option.Value);
myPage.OnEditAction();
};
ContextActions.Add (moreAction);
}
}
So, in your page:
public class PickerPage : ContentPage
{
ListView listView { get; set; }
public PickerPage (OptionListItem [] items)
{
listView = new ListView () ;
Content = new StackLayout {
Children = { listView }
};
var cell = new DataTemplate(() => {return new PickerListCell(this); });
cell.SetBinding (PickerListCell.TextProperty, "Caption");
cell.SetBinding (PickerListCell.CommandParameterProperty, "Value");
listView.ItemTemplate = cell;
listView.ItemsSource = items;
}
void OnEditAction (object sender, EventArgs e)
{
var cell = (sender as Xamarin.Forms.MenuItem).BindingContext as PickerListCell;
await Navigation.PushAsync (new RecordEditPage (recId), true);
}
}
Ok, so with the help of some posts, specifically this one https://forums.xamarin.com/discussion/27881/best-practive-mvvm-navigation-when-command-is-not-available, I came to the following solution, though I'm not perfectly satisfied with the way it looks.
My custom cell now announces when a command is being executed using MessagingCenter:
public class PickerListCell : TextCell
{
public PickerListCell ()
{
var moreAction = new MenuItem { Text = App.Translate ("Edit") };
moreAction.SetBinding (MenuItem.CommandParameterProperty, new Binding ("."));
moreAction.Clicked += async (sender, e) => {
var mi = ((MenuItem)sender);
var option = (PickerListPage.OptionListItem)mi.CommandParameter;
var recId = new Guid (option.Value);
// HERE I send a request to open a new page. This looks a
// bit crappy with a magic string. It will be replaced with a constant or enum
MessagingCenter.Send<OptionListItem, Guid> (this, "PushPage", recId);
};
ContextActions.Add (moreAction);
}
}
And in my PickerPage constructor I added this subscription to the Messaging service:
MessagingCenter.Subscribe<OptionListItem, Guid> (this, "PushPage", (sender, recId) => {
Navigation.PushAsync (new RecordEditPage (recId), true);
});
All this works just find, but I'm not sure if this is the way it was intended to. I feel like the binding should be able to solve this without the Messaging Service, but I can't find out how to bind to a method on the page, only to a model, and I don't want to pollute my model with methods that have dependencies on XF.

UISearchController and MvvmCross

I want add search logic for my application (IOS8). I have simple MvxTableViewController and display my data by UITableViewSource. Here is:
...controller:
MvxViewFor(typeof(MainViewModel))]
partial class MainController : MvxTableViewController
{
public MainController(IntPtr handle) : base(handle) { }
public override void ViewDidLoad()
{
base.ViewDidLoad();
// make background trasnsparent page
this.View.BackgroundColor = UIColor.Clear;
this.TableView.BackgroundColor = UIColor.Clear;
this.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
this.SetBackground ();
(this.DataContext as MainViewModel).PropertyChanged += this.ViewModelPropertyChanged;
}
private void SetBackground()
{
// set blured bg image
}
private void ViewModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var viewModel = this.ViewModel as MainViewModel;
if (e.PropertyName == "Title")
{
this.Title = viewModel.Title;
}
else if (e.PropertyName == "Topics")
{
var tableSource = new TopicTableViewSource(viewModel.Topics);
tableSource.TappedCommand = viewModel.NavigateToChildrenPageCommand;
this.TableView.Source = tableSource;
this.TableView.ReloadData();
}
}
I read about search in IOS and choosed UISearchController for IOS8 app. But I don't understand, how I can add this controller to my view :(
I found sample from Xamarin (TableSearch) - but they don't use UITableViewSource and I don't understand what I should do with this.
I tried add controller:
this.searchController = new UISearchController (this.searchTableController)
{
WeakDelegate = this,
DimsBackgroundDuringPresentation = false,
WeakSearchResultsUpdater = this,
};
this.searchController.SearchBar.SizeToFit ();
this.TableView.TableHeaderView = searchController.SearchBar;
this.TableView.WeakDelegate = this;
this.searchController.SearchBar.WeakDelegate = this;
what should I do in this.searchTableController? Do I need move my display logic there?
Yes. The "searchTableController" should be responsible for the presentation of search results.
Here is the test project (native, not xmarin) which help you understand.
The searchController manages a "searchBar" and "searchResultPresenter". His not need add to a view-hierarchy of the carrier controller. When user starts typing a text in the "searchBar" the "SearchController" automatically shows your SearchResultPresenter for you.
Steps:
1) Instantiate search controller with the SearchResultsPresenterController.
2) When user inputs text in the search-bar you should invoke a your own service for the search. Below a sample of code..
#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = searchController.searchBar.text;
if (searchString.length > 1)
{
// TODO - call your service for the search by string
// this may be async or sync
// When a data was found - set it to presenter
[self.searchResultPresenter dataFound:<found data>];
}
}
3) In the search presenter need to reload a table in the method "dataFound:"
- (void)dataFound:(NSArray *)searchResults
{
_searchResults = searchResults;
[self.tableView reloadData];
}
Here are some advice on how to use the UISearchController with Xamarin.iOS.
Create a new class for the results table view subclassing UITableViewSource. This is gonna be the view responsible of displaying the results. You need to make the items list of that table view public.
public List<string> SearchedItems { get; set; }
In your main UIViewController, create your UISearchController and pass your result table view as an argument. I added some extra setup.
public UISearchController SearchController { get; set; }
public override void ViewDidLoad ()
{
SearchController = new UISearchController (resultsTableController) {
WeakDelegate = this,
DimsBackgroundDuringPresentation = false,
WeakSearchResultsUpdater = this,
};
SearchController.SearchBar.SizeToFit ();
SearchController.SearchBar.WeakDelegate = this;
SearchController.HidesNavigationBarDuringPresentation = false;
DefinesPresentationContext = true;
}
The best way to add the search bar to your UI in term of user experience, in my opinion, is to add it as a NavigationItem to a NavigationBarController.
NavigationItem.TitleView = SearchController.SearchBar;
Add methods to perform the search in the main UIViewController:
[Export ("updateSearchResultsForSearchController:")]
public virtual void UpdateSearchResultsForSearchController (UISearchController searchController)
{
var tableController = (UITableViewController)searchController.SearchResultsController;
var resultsSource = (ResultsTableSource)tableController.TableView.Source;
resultsSource.SearchedItems = PerformSearch (searchController.SearchBar.Text);
tableController.TableView.ReloadData ();
}
static List<string> PerformSearch (string searchString)
{
// Return a list of elements that correspond to the search or
// parse an existing list.
}
I really hope this will help you, good luck.

ObservableCollection filter Selected Item

I have a problem that I don't know how to solve.
I have a observable collection that I filter the items as I type in a textbox the problem is that when I select the filtered item I get the wrong selected index.
For example I have one item after filtering the real selected index is 2 but because it sets the collection as I type it set the index to one if the only filtered item left is one.
So how do I get the right item selected. Like in the mail application to make my question maybe easier to understand
Here is the selection changed event:
private void searchToDoItemsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (searchToDoItemsListBox.SelectedIndex == -1)
return;
NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItemSearch=" + searchToDoItemsListBox.SelectedIndex, UriKind.Relative));
searchToDoItemsListBox.SelectedIndex = -1;
}
And here is for the details page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("selectedItemSearch", out selectedIndexSearch))
{
int indexSearch = int.Parse(selectedIndexSearch);
DataContext = App.ViewModel.AllToDoItems[indexSearch];
}
}
Bind to the SelectedItem
<ListBox SelectedItem="{Binding Selected, Mode=TwoWay}" ItemsSource="Binding={Items}">
</ListBox>
and you have to fields:
public ObservableCollection<ItemType> Items {get;set;} //setted while filtering, does it?
and
private ItemType _selected;
public ItemType Selected
{
get
{
return _selected;
}
set
{
_selected = value;
//here you can save the item.
//For example save the item id, and navigate to DetailsPage
}
}
And then, you can get the item from list:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("selectedItemSearch", out selectedIndexSearch))
{
int id = int.Parse(selectedIndexSearch);
DataContext = GetById(id)
}
}
public ItemType GetByIf(id)
{
for(int i = 0; i < App.ViewModel.AllToDoItems.Count; i++)
{
if(App.ViewModel.AllToDoItems[i].Id == id) return App.ViewModel.AllToDoItems[i];
}
return null;
}
Have done like this now and i get nothing now at all. It navigates but nothings shows.
if (NavigationContext.QueryString.TryGetValue("selectedItemSearch", out selectedIndexSearch))
{
//int indexSearch = int.Parse(selectedIndexSearch);
//DataContext = App.ViewModel.AllToDoItems[indexSearch];
int id = int.Parse(selectedIndexSearch);
DataContext = GetById(id);
}
public object GetById(int id)
{
for(int i = 0; i < App.ViewModel.AllToDoItems.Count; i++)
{
if (App.ViewModel.AllToDoItems[i].ToDoItemId == id)
return App.ViewModel.AllToDoItems[i];
}
return null;
}
The AllToDoItems looks like below, its a observable collection;
This is in the ViewModel this below load the collection from the database.
ToDoItem is the table name in the Model.
// Specify the query for all to-do items in the database.
var toDoItemsInDB = from ToDoItem todo in toDoDB.Items
select todo;
// Query the database and load all to-do items.
AllToDoItems = new ObservableCollection<ToDoItem>(toDoItemsInDB);
The Model looks like this:
public Table<ToDoItem> Items;
//public Table<ToDoFavCategory> Categories;
}
[Table]
public class ToDoItem : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property, and database column.
private int _toDoItemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int ToDoItemId
{
get { return _toDoItemId; }
set
{
if (_toDoItemId != value)
{
NotifyPropertyChanging("ToDoItemId");
_toDoItemId = value;
NotifyPropertyChanged("ToDoItemId");
}
}
}
Its easier maybe to take a look at this link where i have build it from
http://msdn.microsoft.com/en-us/library/hh286405(v=vs.92).aspx

Categories

Resources