android.widget.TimePicker$TimePickerDelegate.getMinute()' on a null object reference - xamarin

We tried of using TimerPickerDialog with Number Picker in Xamarin android. Since we have time interval of 15mins
In Android 10 - getMinute() is returning Null
var classForid = Java.Lang.Class.ForName("com.android.internal.R$id");
var timePickerField = classForid.GetField("timePicker");
[![timePicker][1]][1] = (TimePicker)FindViewById(timePickerField.GetInt(null));
var field = classForid.GetField("minute");
NumberPicker minuteSpinner = (NumberPicker)timePicker
.FindViewById(field.GetInt(null));
minuteSpinner.MinValue = 0;
minuteSpinner.MaxValue = (60 / TimePickerInterval) - 1;
List<string> displayedValues = new List<string>();
for (int i = 0; i < 60; i += TimePickerInterval)
{
displayedValues.Add(i.ToString());
}
minuteSpinner.SetDisplayedValues(displayedValues.ToArray());
We need to get the Minute picker. Screenshot:

Try to create a custom TimePickerDialog ,here is a simple sample,you could check it:
create CustomTimePickerDialog :
public class CustomTimePickerDialog : TimePickerDialog
{
private int _interval = 1;
public CustomTimePickerDialog(Context context, EventHandler<TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView, int interval)
: base(context, ThemeHoloLight, (sender, e) =>
{
callBack(sender, new TimeSetEventArgs(e.HourOfDay, e.Minute * interval));
}, hourOfDay, minute / interval, is24HourView)
{
_interval = interval;
FixSpinner(context, hourOfDay, minute, is24HourView);
}
protected CustomTimePickerDialog(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void SetView(Android.Views.View view)
{
base.SetView(view);
}
void SetupMinutePicker(Android.Views.View view)
{
var numberPicker = FindMinuteNumberPicker(view as ViewGroup);
if (numberPicker != null)
{
int i = _interval;
List<string> values = new List<string>();
values.Add("00");
while (i < 60)
{
if (i < 10)
values.Add("0" + i);
else
values.Add(i.ToString());
i += _interval;
}
numberPicker.MinValue = 0;
numberPicker.MaxValue = values.Count - 1;
numberPicker.SetDisplayedValues(values.ToArray());
}
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
GetButton((int)DialogButtonType.Negative).Visibility = Android.Views.ViewStates.Gone;
this.SetCanceledOnTouchOutside(false);
}
private NumberPicker FindMinuteNumberPicker(ViewGroup viewGroup)
{
for (var i = 0; i < viewGroup.ChildCount; i++)
{
var child = viewGroup.GetChildAt(i);
var numberPicker = child as NumberPicker;
if (numberPicker != null)
{
if (numberPicker.MaxValue == 59)
{
return numberPicker;
}
}
var childViewGroup = child as ViewGroup;
if (childViewGroup != null)
{
var childResult = FindMinuteNumberPicker(childViewGroup);
if (childResult != null)
return childResult;
}
}
return null;
}
private void FixSpinner(Context context, int hourOfDay, int minute, bool is24HourView)
{
try
{
// Get the theme's android:timePickerMode
int MODE_SPINNER = 1;
var styleableClass = Java.Lang.Class.ForName("com.android.internal.R$styleable");
var timePickerStyleableField = styleableClass.GetField("TimePicker");
int[] timePickerStyleable = (int[])timePickerStyleableField.Get(null);
var a = context.ObtainStyledAttributes(null, timePickerStyleable, Android.Resource.Attribute.TimePickerStyle, 0);
var timePickerModeStyleableField = styleableClass.GetField("TimePicker_timePickerMode");
int timePickerModeStyleable = timePickerModeStyleableField.GetInt(null);
int mode = a.GetInt(timePickerModeStyleable, MODE_SPINNER);
a.Recycle();
Android.Widget.TimePicker timePicker = (Android.Widget.TimePicker)findField(Java.Lang.Class.FromType(typeof(TimePickerDialog)), Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), "mTimePicker").Get(this);
var delegateClass = Java.Lang.Class.ForName("android.widget.TimePicker$TimePickerDelegate");
var delegateField = findField(Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), delegateClass, "mDelegate");
var delegatee = delegateField.Get(timePicker);
Java.Lang.Class spinnerDelegateClass;
if (Build.VERSION.SdkInt != BuildVersionCodes.Lollipop)
{
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerSpinnerDelegate");
}
else
{
// TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerClockDelegate");
}
// In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
if (delegatee.Class != spinnerDelegateClass)
{
delegateField.Set(timePicker, null); // throw out the TimePickerClockDelegate!
timePicker.RemoveAllViews(); // remove the TimePickerClockDelegate views
var spinnerDelegateConstructor = spinnerDelegateClass.GetConstructors()[0];
spinnerDelegateConstructor.Accessible = true;
// Instantiate a TimePickerSpinnerDelegate
delegatee = spinnerDelegateConstructor.NewInstance(timePicker, context, null, Android.Resource.Attribute.TimePickerStyle, 0);
delegateField.Set(timePicker, delegatee); // set the TimePicker.mDelegate to the spinner delegate
// Set up the TimePicker again, with the TimePickerSpinnerDelegate
timePicker.SetIs24HourView(Java.Lang.Boolean.ValueOf(is24HourView));
timePicker.Hour = hourOfDay;
timePicker.Minute = minute;
timePicker.SetOnTimeChangedListener(this);
}
// set interval
SetupMinutePicker(timePicker);
}
catch (Exception e)
{
throw new Java.Lang.RuntimeException(e.ToString());
}
}
private static Java.Lang.Reflect.Field findField(Java.Lang.Class objectClass, Java.Lang.Class fieldClass, String expectedName)
{
try
{
var field = objectClass.GetDeclaredField(expectedName);
field.Accessible = true;
return field;
}
catch (Java.Lang.NoSuchFieldException e) { } // ignore
// search for it if it wasn't found under the expected ivar name
foreach (var searchField in objectClass.GetDeclaredFields())
{
if (Java.Lang.Class.FromType(searchField.GetType()) == fieldClass)
{
searchField.Accessible = true;
return searchField;
}
}
return null;
}
}
call like this:
CustomTimePickerDialog timePickerDlg = new CustomTimePickerDialog(this, new EventHandler<TimePickerDialog.TimeSetEventArgs>((o,e)=> { }),
hourOfDay, minute, true,15);// the 15 is the minute interval
timePickerDlg.Show();

Related

TimePicker with 15 minutes interval in xamarin forms

I need to set 15 minutes interval in Time Picker. I have done for iOS. But in Android it is not working.
For iOS I used following code and it is working:
public class CustomTimePickerRenderer : TimePickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
{
 base.OnElementChanged(e);
 var view = (TimePicker)Element;
if (view != null)
{
 var timePicker = (UIDatePicker)Control.InputView;
timePicker.MinuteInterval = 15;
 }
}
}
For Andoroid I am trying with following code:
public class CustomTimePickerRenderer : TimePickerRenderer
{
Context _context;
public CustomTimePickerRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TimePicker> e)
{
base.OnElementChanged(e);
TimePickerDialogIntervals timePickerDlg = new TimePickerDialogIntervals(this.Context, new EventHandler<TimePickerDialogIntervals.TimeSetEventArgs>(UpdateDuration),
Element.Time.Hours, Element.Time.Minutes, true);
var control = new EditText(this.Context);
control.Focusable = false;
control.FocusableInTouchMode = false;
control.Clickable = false;
control.Click += (sender, ea) => timePickerDlg.Show();
control.Text = Element.Time.Hours.ToString("00") + ":" + Element.Time.Minutes.ToString("00");
SetNativeControl(control);
}
void UpdateDuration(object sender, Android.App.TimePickerDialog.TimeSetEventArgs e)
{
Element.Time = new TimeSpan(e.HourOfDay, e.Minute, 0);
Control.Text = Element.Time.Hours.ToString("00") + ":" + Element.Time.Minutes.ToString("00");
}
}
public class TimePickerDialogIntervals : TimePickerDialog
{
public const int TimePickerInterval = 15;
private bool _ignoreEvent = false;
public TimePickerDialogIntervals(Context context, EventHandler<TimePickerDialog.TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView)
: base(context, (sender, e) => {
callBack(sender, new TimePickerDialog.TimeSetEventArgs(e.HourOfDay, e.Minute * TimePickerInterval));
}, hourOfDay, minute / TimePickerInterval, is24HourView)
{
}
protected TimePickerDialogIntervals(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void SetView(Android.Views.View view)
{
SetupMinutePicker(view);
base.SetView(view);
}
void SetupMinutePicker(Android.Views.View view)
{
var numberPicker = FindMinuteNumberPicker(view as ViewGroup);
if (numberPicker != null)
{
numberPicker.MinValue = 0;
numberPicker.MaxValue = 3;
numberPicker.SetDisplayedValues(new String[] { "00", "15", "30", "45" });
}
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
GetButton((int)DialogButtonType.Negative).Visibility = Android.Views.ViewStates.Gone;
this.SetCanceledOnTouchOutside(false);
}
private NumberPicker FindMinuteNumberPicker(ViewGroup viewGroup)
{
for (var i = 0; i < viewGroup.ChildCount; i++)
{
var child = viewGroup.GetChildAt(i);
var numberPicker = child as NumberPicker;
if (numberPicker != null)
{
if (numberPicker.MaxValue == 59)
{
return numberPicker;
}
}
var childViewGroup = child as ViewGroup;
if (childViewGroup != null)
{
var childResult = FindMinuteNumberPicker(childViewGroup);
if (childResult != null)
return childResult;
}
}
return null;
}
}
But Android code is not working. I think the issue is with the number picker in SetupMinutePicker method. I am getting null in number picker.
Please let me know how I can fix this number picker issue or is there any alternate solution to set 15 minutes interval in time picker.
I have found a workaround for Android. The previous override SetView(...) method can not get the NumberPicker now, here we can change the minutes interval in override OnTimeChanged method as follow:
public override void OnTimeChanged(Android.Widget.TimePicker view, int hourOfDay, int minute)
{
if (_ignoreEvent) return;
if (minute % TimePickerInterval != 0)
{
int minuteFloor = minute - (minute % TimePickerInterval);
minute = minuteFloor + (minute == minuteFloor + 1 ? TimePickerInterval : 0);
if (minute == 60)
minute = 0;
_ignoreEvent = true;
view.CurrentMinute = (Java.Lang.Integer)minute;
_ignoreEvent = false;
}
}
The full android renderer code is as follow:
public class CustomTimePickerRenderer : TimePickerRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TimePicker> e)
{
base.OnElementChanged(e);
TimePickerDialogIntervals timePickerDlg = new TimePickerDialogIntervals(this.Context, new EventHandler<TimePickerDialogIntervals.TimeSetEventArgs>(UpdateDuration),
Element.Time.Hours, Element.Time.Minutes, true);
var control = new EditText(this.Context);
control.Focusable = false;
control.FocusableInTouchMode = false;
control.Clickable = false;
control.Click += (sender, ea) => timePickerDlg.Show();
control.Text = Element.Time.Hours.ToString("00") + ":" + Element.Time.Minutes.ToString("00");
SetNativeControl(control);
}
void UpdateDuration(object sender, Android.App.TimePickerDialog.TimeSetEventArgs e)
{
Element.Time = new TimeSpan(e.HourOfDay, e.Minute, 0);
Control.Text = Element.Time.Hours.ToString("00") + ":" + Element.Time.Minutes.ToString("00");
}
}
public class TimePickerDialogIntervals : TimePickerDialog
{
public const int TimePickerInterval = 15;
private bool _ignoreEvent = false;
public TimePickerDialogIntervals(Context context, EventHandler<TimePickerDialog.TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView)
: base(context, (sender, e) => {
callBack(sender, new TimePickerDialog.TimeSetEventArgs(e.HourOfDay, e.Minute * TimePickerInterval));
}, hourOfDay, minute / TimePickerInterval, is24HourView)
{
}
public override void OnTimeChanged(Android.Widget.TimePicker view, int hourOfDay, int minute)
{
base.OnTimeChanged(view, hourOfDay, minute);
if (_ignoreEvent) return;
if (minute % TimePickerInterval != 0)
{
int minuteFloor = minute - (minute % TimePickerInterval);
minute = minuteFloor + (minute == minuteFloor + 1 ? TimePickerInterval : 0);
if (minute == 60)
minute = 0;
_ignoreEvent = true;
view.CurrentMinute = (Java.Lang.Integer)minute;
_ignoreEvent = false;
}
}
}
The effect:
For me the solution from Junior Jiang did not work anymore in Xamarin.Forms 5.0. The reason for this is that the base renderer always calls its own TimePickerDialog. Fortunately you can override the necessary method.
I also changed the behaviour that the minutes jump to the next interval that is nearest to the current position. I think this is a liitle more snappy than pulling completely to the next interval. Also there was a minor calculation error on some specific values for the minute which caused a flickering of the pointer.
public class IntervalTimePickerRenderer : TimePickerRenderer
{
private Context _context;
public IntervalTimePickerRenderer(Context context) : base(context)
{
_context = context;
}
protected override TimePickerDialog CreateTimePickerDialog(int hours, int minutes)
{
return new TimePickerDialogIntervals(
Context,
UpdateDuration,
hours,
minutes,
DateFormat.Is24HourFormat(_context));
}
void UpdateDuration(object sender, TimePickerDialog.TimeSetEventArgs e)
{
Element.Time = new TimeSpan(e.HourOfDay, e.Minute, 0);
Control.Text = Element.Time.Hours.ToString("00") + ":" + Element.Time.Minutes.ToString("00");
Element.Unfocus();
}
}
public class TimePickerDialogIntervals : TimePickerDialog
{
public const int TimePickerInterval = 15;
private bool _ignoreEvent = false;
public TimePickerDialogIntervals(
Context context,
EventHandler<TimeSetEventArgs> callBack,
int hourOfDay,
int minute,
bool is24HourView)
: base(context,
(sender, e) =>
{
callBack(sender, new TimePickerDialog.TimeSetEventArgs(e.HourOfDay, e.Minute));
},
hourOfDay,
minute,
is24HourView)
{
}
public override void OnTimeChanged(Android.Widget.TimePicker view, int hourOfDay, int minute)
{
base.OnTimeChanged(view, hourOfDay, minute);
if (_ignoreEvent) return;
if (minute % TimePickerInterval != 0)
{
float minuteFactor = (float)minute / TimePickerInterval;
int intervalFactor = (int)Math.Round(minuteFactor, 0);
minute = intervalFactor * TimePickerInterval;
if (minute == 60)
{
minute = 0;
}
_ignoreEvent = true;
view.Minute = minute;
_ignoreEvent = false;
}
}
}

Round Shape Icon or Button On Bottom Tabbed Bar Xamarin Forms

I am trying to get the above look on my tabbed bar in xamarin forms, i tried customizing the tabbed bar using renderer and still was not able to get the expected output
output i am getting
till now this is what i have tried
[assembly: ExportRenderer(typeof(BottomNavTabPage), typeof(BottomNavTabPageRenderer))]
namespace HealthMobile.Droid.Renderers
{
public class BottomNavTabPageRenderer : TabbedPageRenderer
{
private bool _isShiftModeSet;
public BottomNavTabPageRenderer(Context context)
: base(context)
{
}
protected override void OnVisibilityChanged(Android.Views.View changedView, [GeneratedEnum] ViewStates visibility)
{
base.OnVisibilityChanged(changedView, visibility);
var tabs = changedView.FindViewById<TabLayout>(Resource.Id.sliding_tabs);
if (tabs != null)
{
ViewGroup vg = (ViewGroup)tabs.GetChildAt(0);
int tabsCount = vg.ChildCount;
}
}
//protected override void DispatchDraw (global::Android.Graphics.Canvas canvas)
// {
// base.DispatchDraw (canvas);
// SetTabIcons();
// // var tabLayout = (TabLayout)GetChildAt(1);
// }
// private void SetTabIcons()
// {
// var element = this.Element;
// if (null == element)
// {
// return;
// }
// Activity activity = this.Context as Activity;
// if ((null != activity) && (null != activity.ActionBar) && (activity.ActionBar.TabCount > 0))
// {
// for (int i = 0; i < element.Children.Count; i += 1)
// {
// var tab = activity.ActionBar.GetTabAt(i);
// var page = element.Children[i];
// if ((null != tab) && (null != page) && (null != page.Icon)
// && (tab.CustomView == null))
// {
// var resourceId = activity.Resources.GetIdentifier(page.Icon.File.ToLowerInvariant(), "drawable", this.Context.PackageName);
// LinearLayout tabHeader
// = new LinearLayout(activity) { Orientation = Orientation.Vertical };
// ImageView tabImg = new ImageView(activity);
// TextView tabTitle = new TextView(activity);
// tabImg.SetImageResource(resourceId);
// tabTitle.Text = page.Title;
// tabTitle.SetTextColor(Android.Graphics.Color.White);
// tabHeader.AddView(tabTitle);
// tabHeader.AddView(tabImg);
// tab.SetCustomView(tabHeader);
// }
// }
// }
// }
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
var childViews = GetAllChildViews(ViewGroup);
//tab.SetIcon(Resource.Drawable.icon);
var scale = Resources.DisplayMetrics.Density;
var paddingDp = 0;
var dpAsPixels = (int)(paddingDp * scale + 0.5f);
foreach (var childView in childViews)
{
if (childView is BottomNavigationItemView tab)
{
//tab.SetPadding(-50, -100, -50, -100);
}
else if (childView is TextView textView)
{
textView.SetTextColor(Android.Graphics.Color.Transparent);
}
}
}
protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
{
base.SetTabIcon(tab, icon);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
try
{
if (!_isShiftModeSet)
{
var children = GetAllChildViews(ViewGroup);
if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
{
bottomNav.SetShiftMode(false, false);
_isShiftModeSet = true;
}
}
}
catch (Exception e)
{
Console.WriteLine($"Error setting ShiftMode: {e}");
}
}
private List<View> GetAllChildViews(View view)
{
if (!(view is ViewGroup group))
{
return new List<View> {view };
}
var result = new List<View>();
for (int i = 0; i < group.ChildCount; i++)
{
var child = group.GetChildAt(i);
var childList = new List<View> {child};
childList.AddRange(GetAllChildViews(child));
result.AddRange(childList);
}
return result.Distinct().ToList();
}
}
}
i am trying to make this look like this somewhat
output expecting
also i tried setting up the icons but SetTabIcons method never get triggered

How to assign OnActivityResult values to the Listview?

I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}

How can i see multiple pins in maps in xamarin forms

I want to see multiple pins in maps when i open google map.
I used this link as help https://xamarinforms.wordpress.com/2015/07/07/adding-a-bindable-map-with-the-map-behavior/
but i get error in MapBehaviour.cs.here is my code.`
BindableProperty.Create>(
p => p.ItemsSource, null, BindingMode.Default, null, ItemsSourceChanged);//i get error in this page
public class MapBehavior: BindableBehavior<Map>
{
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create<MapBehavior, IEnumerable<ILocationViewModel>>(
p => p.ItemsSource, null, BindingMode.Default, null, ItemsSourceChanged);
public System.Collections.Generic.IEnumerable<ILocationViewModel> ItemsSource
{
get { return (IEnumerable<ILocationViewModel>)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
private static void ItemsSourceChanged(BindableObject bindable, IEnumerable oldValue, IEnumerable newValue)
{
var behavior = bindable as MapBehavior;
if (behavior == null) return;
behavior.AddPins();
}
private void AddPins()
{
var map = AssociatedObject;
for (int i = map.Pins.Count - 1; i >= 0; i--)
{
map.Pins[i].Clicked -= PinOnClicked;
map.Pins.RemoveAt(i);
}
var pins = ItemsSource.Select(x =>
{
var pin = new Pin
{
Type = PinType.SearchResult,
Position = new Position(x.Latitude, x.Longitude),
Label = x.Title,
Address = x.Description,
};
pin.Clicked += PinOnClicked;
return pin;
}).ToArray();
foreach (var pin in pins)
map.Pins.Add(pin);
PositionMap();
}
private void PinOnClicked(object sender, EventArgs eventArgs)
{
var pin = sender as Pin;
if (pin == null) return;
var viewModel = ItemsSource.FirstOrDefault(x => x.Title == pin.Label);
if (viewModel == null) return;
viewModel.Command.Execute(null);
}
private void PositionMap()
{
if (ItemsSource == null || !ItemsSource.Any()) return;
var centerPosition = new Position(ItemsSource.Average(x => x.Latitude), ItemsSource.Average(x => x.Longitude));
var minLongitude = ItemsSource.Min(x => x.Longitude);
var minLatitude = ItemsSource.Min(x => x.Latitude);
var maxLongitude = ItemsSource.Max(x => x.Longitude);
var maxLatitude = ItemsSource.Max(x => x.Latitude);
var distance = MapHelper.CalculateDistance(minLatitude, minLongitude,
maxLatitude, maxLongitude, 'M') / 2;
AssociatedObject.MoveToRegion(MapSpan.FromCenterAndRadius(centerPosition, Distance.FromMiles(distance)));
Device.StartTimer(TimeSpan.FromMilliseconds(500), () =>
{
AssociatedObject.MoveToRegion(MapSpan.FromCenterAndRadius(centerPosition, Distance.FromMiles(distance)));
return false;
});
}
}

Unity prefab acting weird?

I wrote some code that allows the user to instantiate objects in editor mode by loading the input images in streaming assets and then creating objects using these images.
This has worked well, the problem is when I try to create a prefab with one of these objects. For some reason, the image is not saved in the prefab, and so when I load that prefab, I get white images instead of the ones that were in the original gameobject.
Update: It turns out that my background screen is actually working correctly, but none of the other gameobjects are. So I am not sure what is wrong and why it is only working for some objects but not the other.
here is my code:
public class PlacementObject : MonoBehaviour
{
private loadbackgroundImages backgroundReference;
public Sprite mouseShape;
private Image mouseSprite;
private RectTransform mouseMovement;
public Canvas myCanvas;
private int currentState = 0;
private bool canMove = true;
public List<Texture2D> allButtons;
private List<Sprite> allButtonsSprite;
private List<Sprite> allUISprites;
private List<Texture2D> allUIElements;
private int uiButtonStates = 0;
private int uiElementStates = 0;
public GameObject afterImport;
private GameObject clonedObject;
public GameObject child;
public GameObject objectToBeExported;
private bool isLoading = true;
private bool isfinishedUploading;
private Vector2 defaultSize;
// Use this for initialization
void Start()
{
allUIElements = new List<Texture2D>();
allButtons = new List<Texture2D>();
var info = new DirectoryInfo(Application.streamingAssetsPath + "/" + "UIButtons");
var fileInfo = info.GetFiles();
foreach (FileInfo file in fileInfo)
{
if (file.Extension == ".png" || file.Extension == ".jpg")
{
StartCoroutine(uploadButtonImages(System.IO.Path.Combine("file:///" + Application.streamingAssetsPath, "UIButtons/" + file.Name)));
}
}
var info2 = new DirectoryInfo(Application.streamingAssetsPath + "/" + "UIElements");
var fileInfo2 = info2.GetFiles();
foreach (FileInfo file2 in fileInfo2)
{
if (file2.Extension == ".png" || file2.Extension == ".jpg")
{
StartCoroutine(uploadUiImages(System.IO.Path.Combine("file:///" + Application.streamingAssetsPath, "UIElements/" + file2.Name)));
}
}
allButtonsSprite = new List<Sprite>();
allUISprites = new List<Sprite>();
//createSpritesForButtons(allButtons);
// createSpritesForElements(allUIElements);
mouseSprite = GetComponent<Image>();
mouseSprite.sprite = mouseShape;
mouseMovement = GetComponent<RectTransform>();
backgroundReference = FindObjectOfType<loadbackgroundImages>();
isfinishedUploading = true;
defaultSize = mouseMovement.sizeDelta;
}
// Update is called once per frame
void Update()
{
print(isLoading);
if (isfinishedUploading && backgroundReference.isfinished)
{
isLoading = false;
}
Cursor.visible = false;
transform.position = Input.mousePosition;
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out pos);
transform.position = myCanvas.transform.TransformPoint(pos);
if (isLoading == false)
{
if (currentState == 2)
{
mouseSprite.sprite = allUISprites[uiElementStates];
}
if (currentState == 1)
{
mouseSprite.sprite = allButtonsSprite[uiButtonStates];
}
if (Input.GetKeyDown(KeyCode.V))
{
currentState = 0;
mouseSprite.sprite = mouseShape;
mouseMovement.sizeDelta = defaultSize;
}
else if (Input.GetKeyDown(KeyCode.B))
{
currentState = 1;
}
else if (Input.GetKeyDown(KeyCode.N))
{
currentState = 2;
}
if (Input.GetMouseButtonDown(0))
{
placeObject();
}
if (Input.GetAxis("Horizontal") > 0 && canMove)
{
canMove = false;
if (currentState == 0)
{
changeBackgroundNext();
}
else if (currentState == 1)
{
changeButtonNext();
}
else if (currentState == 2)
{
changeElementNext();
}
}
if (Input.GetMouseButton(1))
{
rotateObject();
}
if (Input.GetAxis("Vertical") < 0)
{
if (currentState == 1 || currentState == 2)
{
mouseMovement.sizeDelta -= new Vector2(1, 1);
}
}
if (Input.GetAxis("Vertical") > 0)
{
if (currentState == 1 || currentState == 2)
{
mouseMovement.sizeDelta += new Vector2(1, 1);
}
}
if (Input.GetAxis("Horizontal") < 0 && canMove)
{
canMove = false;
if (currentState == 0)
{
changeBackgroundPrev();
}
else if (currentState == 1)
{
changeButtonPrev();
}
else if (currentState == 2)
{
changeElementPrev();
}
}
if (Input.GetAxis("Horizontal") == 0)
{
canMove = true;
}
if (Input.GetKeyDown(KeyCode.Space))
{
var newBackgroundSprite = backgroundReference.allSprites[backgroundReference.imageIndex];
backgroundReference.imageReference.sprite = newBackgroundSprite;
// exportObject();
// importObject();
#if UNITY_EDITOR
var prefab = PrefabUtility.CreatePrefab( "Assets/Resources/Image.prefab", FindObjectOfType<loadbackgroundImages>().gameObject);
AssetDatabase.Refresh();
#endif
}
}
}
void rotateObject()
{
if (currentState == 1 || currentState == 2)
mouseMovement.eulerAngles += new Vector3(0, 0, 1);
}
private void exportObject()
{
UIData saveData = new UIData();
saveData.inputObject = objectToBeExported;
//Save data from PlayerInfo to a file named players
DataSaver.saveData(saveData, "UI");
}
public void importObject()
{
UIData loadedData = DataSaver.loadData<UIData>("UI");
if (loadedData == null)
{
return;
}
//Display loaded Data
Debug.Log("Life: " + loadedData.inputObject);
afterImport = loadedData.inputObject;
}
private void changeBackgroundNext()
{
backgroundReference.imageIndex++;
if (backgroundReference.imageIndex >= backgroundReference.allSprites.Count)
{
backgroundReference.imageIndex = 0;
}
}
private void changeButtonNext()
{
uiButtonStates++;
if (uiButtonStates >= allButtonsSprite.Count)
{
uiButtonStates = 0;
}
}
private void changeElementNext()
{
uiElementStates++;
if (uiElementStates >= allUISprites.Count)
{
uiElementStates = 0;
}
}
private void changeElementPrev()
{
uiElementStates--;
if (uiElementStates < 0)
{
uiElementStates = allUISprites.Count - 1;
}
}
private void changeButtonPrev()
{
uiButtonStates--;
if (uiButtonStates < 0)
{
uiButtonStates = allButtonsSprite.Count - 1;
}
}
private void changeBackgroundPrev()
{
backgroundReference.imageIndex--;
if (backgroundReference.imageIndex < 0)
{
backgroundReference.imageIndex = backgroundReference.allSprites.Count - 1;
}
}
IEnumerator uploadButtonImages(string url)
{
WWW www = new WWW(url);
yield return www;
if (www != null)
{
allButtons.Add(www.texture);
allButtonsSprite.Add(Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0.5f, 0.5f)));
}
}
private void createSpritesForButtons(List<Texture2D> allTextures)
{
for (int i = 0; i < allTextures.Count; i++)
{
Sprite tempSprite = Sprite.Create(allTextures[i], new Rect(0, 0, allTextures[i].width, allTextures[i].height), new Vector2(0.5f, 0.5f));
tempSprite.name = "Button" + i;
allButtonsSprite.Add(tempSprite);
}
}
IEnumerator uploadUiImages(string url)
{
WWW www = new WWW(url);
yield return www;
print(url);
if (www != null)
{
allUIElements.Add(www.texture);
allUISprites.Add(Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height), new Vector2(0.5f, 0.5f)));
}
}
private void createSpritesForElements(List<Texture2D> allTextures)
{
for (int i = 0; i < allTextures.Count; i++)
{
Sprite tempSprite = Sprite.Create(allTextures[i], new Rect(0, 0, allTextures[i].width, allTextures[i].height), new Vector2(0.5f, 0.5f));
tempSprite.name = "" + i;
allUISprites.Add(tempSprite);
}
}
private void placeObject()
{
if (currentState == 1)
{
var gameObject = Instantiate(child, transform.position, Quaternion.Euler(mouseMovement.eulerAngles.x, mouseMovement.eulerAngles.y, mouseMovement.eulerAngles.z), backgroundReference.transform);
gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(mouseMovement.sizeDelta.x, mouseMovement.sizeDelta.y);
var newSprite = allButtonsSprite[uiButtonStates];
gameObject.GetComponent<Image>().sprite = newSprite;
gameObject.AddComponent<Button>();
}
if (currentState == 2)
{
var gameObject = Instantiate(child, transform.position, Quaternion.Euler(mouseMovement.eulerAngles.x, mouseMovement.eulerAngles.y, mouseMovement.eulerAngles.z), backgroundReference.transform);
gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(mouseMovement.sizeDelta.x, mouseMovement.sizeDelta.y);
var newSprite = allUISprites[uiElementStates];
gameObject.GetComponent<Image>().sprite = newSprite;
}
}
}
When you're changing some object's state via an inspector script you have to tell Unity, that you've done some changes, otherwise it doesn't know that something has happened to objects at the scene. And according to the information about changes on your scene (also when you change it manually, not by script) Unity serializes all data on your scene to save all the information. And when you load scene (doesn't matter in editor or in play mode) Unity deserializes all the objects on scene to show you. As far as serializing/deserializng object is rather expensive operation Unity only does it when it's really necessary - in case of saving scene/object it's only performed when it knows that there're some changes that needs to be saved.
The actual solution of your problem depends on Unity version you're using. Try reading this post. Such things as Undo and MarkAllScenesDirty should help you. For older versions of Unity EditorUtility.SetDirty should help.
So as people pointed out like Vmchar, when you save the prefab using code. it gets saved using the initial state without any of the stuff that got loaded to it during runtime.
I found out a solution for this though, all you need to do is make a script that would save the image by serializing it in streamingassets (plenty of tutorials online on how to serialize image), and then loading it using www stream when needed in the other scene.

Resources