Ripple Effect gone after adding TapGestureRecognizer to ViewCell - xamarin

I added a custom LongPressGestureRecognizer to the ViewCell's root layout to handle certain cases, but after adding it, I find that the ripple effect when tapping the ViewCell is gone on Android. I tried to add back the animation by getting the native view, set background drawable to Android.Resource.Attribute.SelectableItemBackground by using below code
int[] attrs = { Android.Resource.Attribute.SelectableItemBackground };
var ta = CrossCurrentActivity.Current.Activity.ObtainStyledAttributes(attrs);
var drawable = ta.GetDrawable(0);
nativeView.SetBackgroundDrawable(drawable);
ta.Recycle();
Even this doesn't work. Any other way to make it work?

For those who want to know, I discarded the custom long press gesture recognizer way of achieving the goal, since it's the wrong way of doing things. On Android, we should use ItemLongClick event instead. Here is what I did, first, find out the native ListView through some method, my way is to first get the renderer of the ListView, then get underlying ListView. Another way is to use below code to find the ListView, but this way requires more work if you have multiple ListView
public static List<T> FindViews<T>(this ViewGroup viewGroup) where T : View
{
var result = new List<T>();
var count = viewGroup.ChildCount;
for (int i = 0; i < count; i++)
{
var child = viewGroup.GetChildAt(i);
var item = child as T;
if (item != null)
{
result.Add(item);
}
else if (child is ViewGroup)
{
var innerResult = FindViews<T>(child as ViewGroup);
if (innerResult != null)
{
result.AddRange(innerResult);
}
}
}
return result;
}
var rootView =(ViewGroup)CurrentActivity.Window.DecorView.RootView
var nativeListView = rootView.FindView<Android.Widget.ListView>();
Then override the OnAppearing method of the Page, in it, attach ItemLongClick event handler. Also override OnDisappearing method, in it, detach the ItemLongClick event handler. This is important. Simply add ItemLongClick event handler in constructor seems not working.

Related

MvvmCross migration causing a Xamarin Custom iOS View Presenter issue

While creating a CustomIosViewPresenter (of type MvxIosViewPresenter), in MVVMCross 5.x, there was a Show override that I was able to use to get the IMvxIosView so as to update the UIViewController presentation style using the PresentationValues from the ViewModel.
I had this code and it worked:
// Worked before
public override void Show(IMvxIosView view, MvvmCross.ViewModels.MvxViewModelRequest request)
{
if (request.PresentationValues != null)
{
if (request.PresentationValues.ContainsKey("NavigationMode") &&
request.PresentationValues["NavigationMode"] == "WrapInModalWithNavController")
{
var vc = view as IModalPresentation;
vc.ModalPresentationAttribute = new MvxModalPresentationAttribute
{
WrapInNavigationController = true,
ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen,
ModalTransitionStyle = UIModalTransitionStyle.CoverVertical
};
}
}
base.Show(view, request);
}
But after migrating to MvvmCross 7.1, the older override doesn't work anymore and I have to use this instead, but there is no view passed into the Show override, how do I get it?
I tried this code below, but view is null and it's not able to cast it this way var view = viewType as IMvxIosView;
// Doesn't work now
public override Task<bool> Show(MvxViewModelRequest request)
{
if (request.PresentationValues != null)
{
if (request.PresentationValues.ContainsKey("NavigationMode") &&
request.PresentationValues["NavigationMode"] == "WrapInModalWithNavController")
{
var viewsContainer = Mvx.IoCProvider.Resolve<IMvxViewsContainer>();
var viewType = viewsContainer.GetViewType(request.ViewModelType);
var view = viewType as IMvxIosView;
var vc = view as IModalPresentation;
vc.ModalPresentationAttribute = new MvxModalPresentationAttribute
{
WrapInNavigationController = true,
ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen,
ModalTransitionStyle = UIModalTransitionStyle.CoverVertical
};
}
}
return base.Show(request);
}
The reason I need this is because without this function when I close the special flow of view controllers that need this, its not closing all the view controllers in that flow, it closes only one of them at a time.
What you would normally do with MvvmCross if you want to navigate within a Modal ViewController is firstly add a MvxModalPresentationAttribute to the modal that will host the rest of the navigation where you set WrapInNavigationController to true.
For the children, it would just be regular child navigation, no attributes needed.
If you then want to control how the modal is popping you would create your own MvxPresentationHint and register it in your presenter using AddPresentationHintHandler.
Then you would in your ViewModel where you want to change the presentation call NavigationService.ChangePresentation(your hint).
As for the Presentation Hint, it should probably just call CloseModalViewControllers and that would probably do what you want.
TLDR: Feel for the developers that will come after you and build stuff the right way
So I dug into the MvvmCross MvxIosViewPresenter source code and was able to use this new override CreateOverridePresentationAttributeViewInstance()
I needed the request object to see the presentation values so I updated the Show function that gets called before the other override as follows:
MvxViewModelRequest _request;
public override Task<bool> Show(MvxViewModelRequest request)
{
_request = request;
return base.Show(request);
}
And I was able to get the ViewController this way, in order to selectively present it as a modal:
{
var view = base.CreateOverridePresentationAttributeViewInstance(viewType);
if (_request.PresentationValues.ContainsKey("NavigationMode") &&
_request.PresentationValues["NavigationMode"] == "WrapInModalWithNavController")
{
var vc = view as IModalPresentation;
vc.ModalPresentationAttribute = new MvxModalPresentationAttribute
{
WrapInNavigationController = true,
ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen,
ModalTransitionStyle = UIModalTransitionStyle.CoverVertical
};
return vc;
}
return view;
}
And then the closing of the modal was another challenge, that I was able to figure out using the TryCloseViewControllerInsideStack and ChangePresentation overrides

RecyclerView Click event

I have created a RecyclerView adapter and I'm trying to start an activity when a row is clicked:
public override OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyViewHolder viewHolder = (MyViewHolder)holder;
viewHolder.MyView.Click += (sender, e) =>
{
var context = viewHolder.MyView.Context;
var intent = new Intent(context, typeof(DetailActivity));
context.StartActivity(intent);
}
}
When I click the first row it will take me to the activity like I want. If I scroll down so that the first row is rebound and then scroll back to the top again and then click the first row then my Click event fires twice. Once for the first row that was bound and then again for a row that was bound when I scrolled.
Is there an event you need to handle to unregister the click events?
I believe the standard pattern is to setup your clickhandlers in the constructor of the ViewHolder. Then in OnBindViewHolder, you update the Views/Data inside the ViewHolder.
Something like this (not compiled code):
Adapter:
public override OnBindViewHolder()
{
MyViewHolder viewHolder = (MyViewHolder)holder;
viewHolder.SetData(whatever data you care about);
}
MyViewHolder:
public MyViewHolder(View view) : base(view)
{
MainView = view;
MainView.Click += (sender, e) =>
{
var context = MainView.Context;
var intent = new Intent(context, typeof(DetailActivity));
context.StartActivity(intent);
}
}
Doing it this way keeps the Adapter cleaner by putting business logic in the ViewHolder, and also prevents your click handlers from being constantly setup and torn down as you scroll.

Multiple Custom Cell's in a ListView (Cross Platform)

Currently with ListView's I've only found that you can create a template for cells, which makes each cell look exactly the same. You can't have multiple custom cells in the listview. There are work-arounds like hiding the content in the cell depending on the content, but this seems pretty hacky.
The reason I want to use a listview over a tableview is because we plan on doing inserts, deletions, dynamically showing certain cells, and listview's can be binded to a data source.
Create your own ViewCell which overrides binding context change method. When the binding changes set the ViewCell's view to one that matches the type of view model and also set the height of the cell. Below is a quick sample that should give you an idea how to accomplish it.
public class DataTemplateCell1 : ViewCell
{
protected override void OnBindingContextChanged()
{
var vm1 = this.BindingContext as ViewModel1;
if (vm1 != null)
{
this.View = new View1() { HeightRequest = 40 };
this.Height = this.View.HeightRequest;
return;
}
var vm2 = this.BindingContext as ViewModel2;
if (vm2 != null)
{
this.View = new View2() { HeightRequest = 80 };
this.Height = this.View.HeightRequest;
return;
}
base.OnBindingContextChanged();
}
}

How to Work With GUI button in unity

I want to get user input through GUI Button in unity3d unityscript. I have write this script to get user input through keyboard
var f_hor : float = Input.GetAxis("Horizontal");
//Get Vertical move - move forward or backward
var f_ver : float = Input.GetAxis("Vertical");
if (f_ver < 0) {
b_isBackward = true;
} else {
b_isBackward = false;
}
its work fine and its give me 0 and 1 accordingly..But i want the same action through GUI button.Like if i have four GUI button..and they work same as this did...I can make GUI button in ONGUI function..But how can i achieve this functionaility...Any help
Altough I don't know if it is the best way to go (Unity's gui element are not the best for ingame HUD or menu), this should do the job:
private bool buttonPressed = false;
public void Update()
{
if (buttonPressed)
{
//do what you want
buttonPressed = false;
}
}
Sorry for using C# code, but I don't know JS. It should be easy to translate tough.
public void OnGui()
{
Rect rect = new Rect(...); //your button dimension
if (GUI.Button(rect, "AButton")
{
buttonPressed = true;
}
}
EDIT:
If you want to manually handle input from mouse you can use methods of MonoBehavior such as OnMouseDown or OnMouseUp.
Alternatively you can check from inside Update if a mouse event occured, have a look at Input.GetMouseButton or similar methods of Input class.

Making an NSTableView behave like a WPF StackPanel

I'm trying to implement a vertical StackPanel equivalent in my MonoMac project and am having trouble figuring it out. I am not using interface builder but creating the controls programmatically (this is a restriction). I tried using a CollectionView but all items in that control are sizing to the same height.
Looking around the internet, it seems NSTableView is the way to go, but I'm not sure how to do it, especially with C# while using a MonoMac target. CollectionView was somewhat more straightforward with the CollectionViewItem.ItemPrototype allowing me to create the views I want to render. But with an NSTableView, it seems like I can only specify a data source that returns the NSObjects I want to display. How do I grab this data and then bind them to the view I want to stick in there?
I would prefer C# code but I'm at a stage where I'll accept any and all help!
I was finally able to get it working. Here is some code for anyone who wants to try it out. Basically, we need to write NSTableViewDelegates for the required functions. This implementation also doesn't cache the controls or anything. The Cocoa API documentation mentioned using an identifier to reuse the control, or something, but the identifier field is get-only in MonoMac.
I also ended up implementing my NSTableViewDelegate functions in my data-source itself which I am sure is not kosher at all, but I'm not sure what the best practice is.
Here's the data source class:
class MyTableViewDataSource : NSTableViewDataSource
{
private NSObject[] _data;
// I'm coming from an NSCollectionView, so my data is already in this format
public MyTableViewDataSource(NSObject[] data)
{
_data = data;
}
public override int GetRowCount(NSTableView tableView)
{
return _data.Length;
}
#region NSTableViewDelegate Methods
public NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, int row)
{
// MyViewClass extends NSView
MyViewClass result = tableView.MakeView("MyView", this) as MyViewClass;
if (result == null)
{
result = new MyViewClass(_data[row]);
result.Frame = new RectangleF(0, 0, tableView.Frame.Width, 100); // height doesn't matter since that is managed by GetRowHeight
result.NeedsDisplay = true;
// result.Identifier = "MyView"; // this line doesn't work because Identifier only has a getter
}
return result;
}
public float GetRowHeight(NSTableView tableView, int row)
{
float height = FigureOutHeightFromData(_data[row]); // run whatever algorithm you need to get the row's height
return height;
}
#endregion
}
And here's the snippet that programmatically creates the table:
var tableView = new NSTableView();
var dataSource = new MyTableViewDataSource();
tableView.DataSource = dataSource;
tableView.HeaderView = null; // get rid of header row
tableView.GetViewForItem = dataSource.GetViewForItem;
tableView.GetRowHeight = dataSource.GetRowHeight;
AddSubView(tableView);
So, it is not a perfect StackPanel because one needs to manually calculate row heights, but it's better than nothing.

Resources