how to set xaml mapcontrol mapicon always visible - xaml

I'm fairly new to programming in XAML and I'm making a test application on windows phone 8.1 emulator with a MapControl.
I wanted to add a MapIcon to my map but the icon doesn't appear when the map is zoomed out. I've searched the internet and couldn't find anything regarding my problem.
I want my zoomlevel 12 and show the mapicon on that zoomlevel.
namespace TEST.APPLICATION
{
public partial class MapView : Page
{
Geolocator geo = null;
public MapView()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
map.Center = new Geopoint(new BasicGeoposition()
{
Latitude = 51.5856935784736,
Longitude = 4.79448171225132
});
map.ZoomLevel = 12;
displaySightings();
}
private void displaySightings()
{
MapIcon sighting1 = new MapIcon();
sighting1.Location = new Geopoint(new BasicGeoposition()
{
Latitude = 51.5940,
Longitude = 4.7795
});
//sighting1.NormalizedAnchorPoint = new Point(0.5, 1.0);
sighting1.Title = "VVV";
map.MapElements.Add(sighting1);
}
}
Is there any way to make the MapIcon always visible?

The MapIcon is not guaranteed to be shown. It may be hidden when it obscures other elements or labels on the map.
For some stupid reason, Microsoft thought that labels and other map elements should outrank map icons when rendering the display. So, if you're making an app displaying the locations of all the nearby Starbucks, the name of the high school across the street from the Starbucks is more important than the pushpin, according to them.
You'll need to render the pushpins using XAML instead.

Related

PagerAdapter always getting called two times in ViewPager

I am trying to make a slider between TouchImageView and PlayerView (Exoplayer) but I am unable to catch up with certain issues that are persisting even after several changes. All the suggestions and answers are welcome. Pardon my questioning skills and please let me know if more inputs are needed for your analysis. Kindly also let me know if there is any other alternative to successfully meet my expectations of properly implementing views smoothly in ViewPager.
Problem description:-
Issues related to click on view :-
When the image is clicked, the audio of next video (if any) starts playing in background.
The same issue is with PlayerView. When the video thumbnail is clicked, the audio of clicked video as well as next video plays together.
Issues related to slider :-
When an we slide and reach to an image preceding to a video, the audio starts playing in background. However, after sliding once toward video and sliding again in forward or backward direction from video for once, the audio stops. But this issue persists after viewing more than one images in forward or backward direction of video.
Attempts made by me to solve this issue :-
I tried to use playerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {...}) method in PagerAdapter to handle player states while sliding between views. Unfortunately, I was unable to grasp to use different player states.
I also tried to use viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {...} method in StatusViewer class.
StatusViewer Java class (Setting PagerAdapter class object inViewPager) :-
modelFeedArrayList = (ArrayList<File>) getIntent().getSerializableExtra("modelFeedArrayList");
position = intent.getIntExtra("position", 0);
ImageSlideAdapter imageSlideAdapter = new ImageSlideAdapter(this,modelFeedArrayList,position);
viewPager.setAdapter(imageSlideAdapter);
viewPager.setCurrentItem(position);
viewPager.setOffscreenPageLimit(0);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
File currentFile = modelFeedArrayList.get(position);
String filePath = currentFile.toString();
if (filePath.endsWith(".jpg") || currentPage == position){
currentPage = position;
ImageSlideAdapter.player.pause();
}
else {
currentPage = position;
ImageSlideAdapter.player.play();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
ImageSliderAdapter (PagerAdapter) (code mentioned below is inside instantiateItem):-
File currentFile = modelFeedArrayList.get(position);
String filePath = currentFile.toString();
if (currentFile.getAbsolutePath().endsWith(".mp4")) {
statusImageView.setVisibility(View.GONE);
playerView.setVisibility(View.VISIBLE);
player = new ExoPlayer.Builder(context).build();
MediaItem mediaItem = MediaItem.fromUri(filePath);
player.addMediaItem(mediaItem);
playerView.setPlayer(player);
player.prepare();
playerView.setBackgroundColor(context.getResources().getColor(android.R.color.black));
playerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
Log.d("Filepath", filePath);
Log.d("Position", "" + position);
}
#Override
public void onViewDetachedFromWindow(View v) {
if (filePath.endsWith(".jpg") || currentPage == position || modelFeedArrayList.get(currentPage).getAbsolutePath().endsWith(".jpg")){
currentPage = position;
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.release();
Objects.requireNonNull(playerView.getPlayer()).release();
}
}
});
} else {
playerView.setVisibility(View.GONE);
statusImageView.setVisibility(View.VISIBLE);
Glide.with(context).load(modelFeedArrayList.get(position)).into(statusImageView);
statusImageView.setBackgroundColor(context.getResources().getColor(android.R.color.black));
}
Objects.requireNonNull(container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(#NonNull #NotNull ViewGroup container, int position, #NonNull #NotNull Object object) {
container.removeView((ConstraintLayout) object);
}
Thank you StackOverflow community for viewing this question. I resolved the above issue by below mentioned modifications :-
Changes in ImageSliderAdapter (PagerAdapter) :-
-> Below mentioned code was added in onViewAttachedToWindow(View v) :-
if (filePath.endsWith(".jpg") || currentPage == position || modelFeedArrayList.get(currentPage).getAbsolutePath().endsWith(".jpg")){
currentPage = position;
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
if (filePath.endsWith(".mp4")){
player.pause();
Objects.requireNonNull(playerView.getPlayer()).pause();
}
else {
player.play();
Objects.requireNonNull(playerView.getPlayer()).play();
}
}
-> Below mentioned code was added in onViewDetachedFromWindow(View v) :-
if (filePath.endsWith(".mp4")){
player.release();
Objects.requireNonNull(playerView.getPlayer()).release();
}
-> player.play() was added after player.prepare().
Changes in StatusViewer Java class :-
-> The below changes cured the issue of player malfunctioning and player's play state and release state. I used the smoothScroll: false in setCurrentItem.
viewPager.setCurrentItem(position,false);

Change the backcolor of current line of caret position [duplicate]

I have uploaded a image of what i want to achive...
So as you can see i want to highlight the line i click on [And update it on _textchanged event!
Is there any possible way of doing this in any colour... doesnt have to be yellow. I have searched alot but i cant understand how to get the starting length and end length and all of that.
It has confused me alot and i don;'t understand and would require some help.
Thanks for all help that is given in this thread. Also it is windows form. Im making a notepad app like notepad++ or some other notepad app... .NET Windows Form C# RichTextBox
You'll need to create your own control that inherits from RichTextBox and use that control on your form. Since the RichTextBox does not support owner drawing, you will have to listen for the WM_PAINT message and then do your work in there. Here is an example that works fairly well, though the line height is hard coded right now:
public class HighlightableRTB : RichTextBox
{
// You should probably find a way to calculate this, as each line could have a different height.
private int LineHeight = 15;
public HighlightableRTB()
{
HighlightColor = Color.Yellow;
}
[Category("Custom"),
Description("Specifies the highlight color.")]
public Color HighlightColor { get; set; }
protected override void OnSelectionChanged(EventArgs e)
{
base.OnSelectionChanged(e);
this.Invalidate();
}
private const int WM_PAINT = 15;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_PAINT)
{
var selectLength = this.SelectionLength;
var selectStart = this.SelectionStart;
this.Invalidate();
base.WndProc(ref m);
if (selectLength > 0) return; // Hides the highlight if the user is selecting something
using (Graphics g = Graphics.FromHwnd(this.Handle))
{
Brush b = new SolidBrush(Color.FromArgb(50, HighlightColor));
var line = this.GetLineFromCharIndex(selectStart);
var loc = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(line));
g.FillRectangle(b, new Rectangle(loc, new Size(this.Width, LineHeight)));
}
}
else
{
base.WndProc(ref m);
}
}
}

Xamarin.Android how to remember the position of items in a recyclerview

I have a recyclerview set up in xamarin.android as per the code in this link
https://www.appliedcodelog.com/2019/08/reorder-list-items-by-drag-and-drop-in.html
My question is, how can I remember the position of these items when the app is restarted etc. When the user adds items they are inserted at adapter position 0,1,2,3 etc but when they close the app and come back in, it is not always in the same order.
The user can also rearrange by drag and drop so this seems to add even more confusion!
Currently I have the items in the recyclerview being saved by converting the list to Json and loading when the app opens again but as I said, the items aren't always in the same order as before the app was closed.
Can anyone advise the best way to do this? I have tried to add the item name and position number to a list converting to json then trying to insert the item at the saved position index but can't get it to work..
Thanks
Do you want to achieve the result like following GIF?
You can use PreferenceManager to store position of items(Before store data, I will Serialize data) in a recyclerview.
You can override OnPause() method, this method will be executed when application is background or app is killed. So we can store the position and data in this method.Here is code about ReOrderActivity
[Activity(Label = "ReOrderList")]
public class ReOrderActivity : Activity, IOnStartDragListener
{
private ItemTouchHelper _mItemTouchHelper;
public static ObservableCollection<string> ResourceList;
private RecyclerView _resourceReorderRecyclerView;
ReOrderAdapters resourceAdapter;
ISharedPreferences prefs;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ReOrderLayout);
prefs = PreferenceManager.GetDefaultSharedPreferences(this);
GetCollection();
resourceAdapter = new ReOrderAdapters(ResourceList, this);
// Initialize the recycler view.
_resourceReorderRecyclerView = FindViewById<RecyclerView>(Resource.Id.ResourceReorderRecyclerView);
Button mDone = FindViewById<Button>(Resource.Id.mDone);
mDone.Click += MDone_Click;
_resourceReorderRecyclerView.SetLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.Vertical, false));
_resourceReorderRecyclerView.SetAdapter(resourceAdapter);
_resourceReorderRecyclerView.HasFixedSize = true;
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(resourceAdapter);
_mItemTouchHelper = new ItemTouchHelper(callback);
_mItemTouchHelper.AttachToRecyclerView(_resourceReorderRecyclerView);
}
protected override void OnPause()
{
base.OnPause();
string ConvertData = JsonConvert.SerializeObject(ResourceList);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("ObservableCollection_ConvertData", ConvertData);
// editor.Commit(); // applies changes synchronously on older APIs
editor.Apply(); // applies changes asynchronously on newer APIs
}
private void MDone_Click(object sender, System.EventArgs e)
{
resourceAdapter.AddItem("Add item");
}
public void OnStartDrag(RecyclerView.ViewHolder viewHolder)
{
_mItemTouchHelper.StartDrag(viewHolder);
}
//Added sample data record here
public void GetCollection()
{
//ISharedPreferencesEditor editor = prefs.Edit();
//editor.PutString("ObservableCollection_ConvertData", "");
//editor.Apply();
string ConvertData = prefs.GetString("ObservableCollection_ConvertData","");
if(string.IsNullOrEmpty(ConvertData))
{
ResourceList = new ObservableCollection<string>();
ResourceList.Add("OnPause()");
ResourceList.Add("OnStart()");
ResourceList.Add("OnCreate()");
}
else
{
ResourceList= JsonConvert.DeserializeObject<ObservableCollection<string>>(ConvertData);
}
//var or= ResourceList.ToString();
}
}
}
You can download my demo
https://drive.google.com/file/d/1mQTKf3rlcIVnf2N97amrqtnrSCRk-8ZW/view?usp=sharing

Bing maps resizable polygon

I am trying to implement the ability for a user to draw and refine a polygon on a Bing Map control.
I have added a shape layer, and overridden the tap events to draw a simple polygon and that all works perfectly. I would like to further refine the control so that a user can drag and drop any of Location objects of the drawn polygon to alter its shape, but I'm not having any luck.
I have tried to add a MapItemControl, bound to the Locations property of my polygon, but without success - I don't see the pins appear on the map, even though my polygon does render correctly. Presumably the Locations collection isn't notifying the UI of any changes to the collection, so I may have to maintain a separate collection for these pins.
Once I get this going, however, I still need to be able to drag and drop the pins around to modify the polygon. Has anyone implemented this on Windows 8 that could share some thoughts, please?
EDIT
I now have my pins showing the Locations collection on the map. I'd ideally like to tie these back to the Locations collection of the polygon, but beggars can't be choosers. I now just need to be able to drag the pins around.
I added a drag handle module to the polygon in order to edit each point in the polygon. This is the walk-through I used.
Drag Handle Module
This is for version 7.0. Not sure which version you are using, but it is easily adaptable.
Edit I did this in javascript/html. Just noticed you tagged this as windows 8. Curious, are you making a silver-light control for windows 8 phones?
WPF C# Solution
Here is what I came up with and it is very easy to implement, all you need to do is hook my event onto your MapPolygon object. The idea behind the code, is once you click on the polygon, we place a pushpin (which we create events so that we can drag it) at each vertice on the polygon. As we drag and drop each pushpin we adjust the polygon.Locations as applicable.
polygon.MouseDown += new MouseButtonEventHandler(polygon_MouseDownResize);
And a way to exit the resize event, I choose to just hook onto the key down and used 'esc' to stop editing, but you can do this on right click or any other event you choose to. All your doing is clearing pushPinVertices list and resetting event variables.
// === Editable polygon Events ===
private bool _shapeEdit;
public MapPolygon selectedPoly { get; set; }
public List<Pushpin> pushPinVertices { get; set; }
void polygon_MouseDownResize(object sender, MouseButtonEventArgs e)
{
if (!_shapeEdit && selectedPoly == null)
{
_shapeEdit = true;
selectedPoly = sender as MapPolygon;
pushPinVertices = new List<Pushpin>();
int i = 0;
foreach (Microsoft.Maps.MapControl.WPF.Location vertice in selectedPoly.Locations)
{
Pushpin verticeBlock = new Pushpin();
// I use a template to place a 'vertice marker' instead of a pushpin, il provide resource below
verticeBlock.Template = (ControlTemplate)Application.Current.Resources["PushPinTemplate"];
verticeBlock.Content = "vertice";
verticeBlock.Location = vertice;
verticeBlock.MouseDown += new MouseButtonEventHandler(pin_MouseDown);
verticeBlock.MouseUp += new MouseButtonEventHandler(pin_MouseUp);
myMap.Children.Add(verticeBlock);
pushPinVertices.Add(verticeBlock);
i++;
}
}
}
private void myMap_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Escape)
{
if (_shapeEdit && selectedPoly != null)
{
foreach (Pushpin p in pushPinVertices)
{
myMap.Children.Remove(p);
}
_shapeEdit = false;
selectedPoly = null;
}
}
}
// Note: I needed my window to pass bing maps the keydown event
private void Window_KeyDown(object sender, KeyEventArgs e)
{
myMap_KeyDown(sender, e);
}
// === Editable polygon Events ===
// ==== Draggable pushpin events =====
Vector _mouseToMarker;
private bool _IsPinDragging;
public Pushpin SelectedPushpin { get; set; }
void pin_MouseUp(object sender, MouseButtonEventArgs e)
{
LocationCollection locCol = new LocationCollection();
foreach (Pushpin p in pushPinVertices)
{
locCol.Add(p.Location);
}
selectedPoly.Locations = locCol;
bingMapRefresh();
_IsPinDragging = false;
SelectedPushpin = null;
}
void pin_MouseDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
SelectedPushpin = (Pushpin)sender;
_IsPinDragging = true;
_mouseToMarker = Point.Subtract(
myMap.LocationToViewportPoint(SelectedPushpin.Location),
e.GetPosition(myMap));
}
private void myMap_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (_IsPinDragging && SelectedPushpin != null)
{
SelectedPushpin.Location = myMap.ViewportPointToLocation(Point.Add(e.GetPosition(myMap), _mouseToMarker));
e.Handled = true;
}
}
}
// ==== Draggable pushpin events =====
// Nice little maprefresh I found online since the bingmap WPF doesnt always seem to update elements after certain event orders
private void bingMapRefresh()
{
//myMap.UpdateLayout();
var mapCenter = myMap.Center;
mapCenter.Latitude += 0.00001;
myMap.SetView(mapCenter, myMap.ZoomLevel);
}
As for the resource to overwrite the pushpin icon, I just used an ImageBrush an made a small white square. Note you may need to adjust the Margin property depending on how long / wide you make your marker. This is because generally the pushpin is anchored above the location by default.
<Application.Resources>
<ControlTemplate x:Key="PushPinTemplate">
<Grid>
<Rectangle Width="10" Height="10" Margin="0 35 0 0">
<Rectangle.Fill>
<ImageBrush ImageSource="pack://application:,,,/Images/DragIcon.gif"/>
</Rectangle.Fill>
</Rectangle>
</Grid>
</ControlTemplate>
</Application.Resources>

Using KinectColorViewer in SDK1.5

I am trying to use a KinectColorViewer in a project using Kinect for windows (sdk 1.5). In the kinect explorer example, the KinectColorViewer componant had a KinectSensorManager component that is binded. In the xaml file we have:
<kt:KinectColorViewer x:Name="ColorViewer" KinectSensorManager="{Binding KinectSensorManager}" CollectFrameRate="True" RetainImageOnSensorChange="True" />
I have a lot of trouble reproduccing the same concept in other projects. I have used the Microsoft.Kinect.Toolkit's KinectSensorChooser, KinectSensorChooserUI and the Mirosoft.Sampels.Kinect.wpfviewers KinectColorViewer. Tried to bind the KinectSensorManager of The colorViewer to the UI element and follows.
<my:KinectColorViewer Width="200" Height="200" HorizontalAlignment="Left" Margin="198,12,0,0" Name="kinectColorViewer1" VerticalAlignment="Top" KinectSensorManager="{Binding ElementName=kinectSensorChooserUI1, Path=KinectSensorChooser.Kinect}" />
both attempts were unsuccesfull. Has anyone used the ColorViwer, DepthViwer and SkeletonViewer using the new SDK? Figuring that our would be great...
To bind the KinectSensorManager, I added the following code to the back end:
public partial class MainWindow : Window
{
public KinectSensorManager KinectSensorManager { get; set;}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
KinectSensorManager = new KinectSensorManager();
KinectSensorManager.KinectSensorChanged += new EventHandler<KinectSensorManagerEventArgs<KinectSensor>>(KinectSensorManager_KinectSensorChanged);
// Look through all sensors and start the first connected one.
// This requires that a Kinect is connected at the time of app startup.
foreach (var potentialSensor in KinectSensor.KinectSensors)
{
if (potentialSensor.Status == KinectStatus.Connected)
{
this.sensor = potentialSensor;
break;
}
}
if (null != this.sensor)
{
// Turn on the skeleton stream to receive skeleton frames
this.sensor.SkeletonStream.Enable();
this.sensor.DepthStream.Enable();
this.sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
this.sensor.AllFramesReady += new System.EventHandler<AllFramesReadyEventArgs>(sensor_AllFramesReady);
this.sensor.SkeletonFrameReady += this.SensorSkeletonFrameReady;
// Start the sensor!
try
{
this.sensor.Start();
}
catch (IOException)
{
this.sensor = null;
}
var kinectSensorBinding = new Binding("KinectSensor") { Source = this.sensor };
BindingOperations.SetBinding(this.KinectSensorManager, KinectSensorManager.KinectSensorProperty, kinectSensorBinding);
}
if (null == this.sensor)
{
this.statusBarText.Text = Properties.Resources.NoKinectReady;
}
}
and the Xaml file:
<kt:KinectColorViewer Width="191" Height="83" Grid.Column="3" KinectSensorManager="{Binding KinectSensorManager}" HorizontalAlignment="Left" Margin="17,236,0,0" Name="kinectColorViewer1" VerticalAlignment="Top" />
but I still dont get any color stream.
You binding statement is incorrect. "KinectSensorChooser.Kinect" is a reference to hardware (i.e., the Kinect) selected by the KinectSensorChooser -- it is not the KinectSensorManager.
You should be binding to the KinectSensorManager in the same way the examples show you. Is there something special you are trying to do that would lead you to bind it differently?
Your main class should start out something like this:
// automatically finds a Kinect for you
private readonly KinectSensorChooser sensorChooser = new KinectSensorChooser();
// the bindable sensor property
public KinectSensorManager KinectSensorManager { get; private set; }
public MainViewModel()
{
if (IsInDesignMode) {
// load design mode only content
}
else
{
// initialize the Kinect sensor manager
KinectSensorManager = new KinectSensorManager();
KinectSensorManager.KinectSensorChanged += this.KinectSensorChanged;
// locate an available sensor
sensorChooser.Start();
// bind chooser's sensor value to the local sensor manager
var kinectSensorBinding =
new Binding("Kinect") { Source = this.sensorChooser };
BindingOperations.SetBinding(
this.KinectSensorManager,
KinectSensorManager.KinectSensorProperty,
kinectSensorBinding);
}
}
#region Kinect Discovery & Setup
private void KinectSensorChanged(object sender,
KinectSensorManagerEventArgs<KinectSensor> args)
{
if (null != args.OldValue)
UninitializeKinectServices(args.OldValue);
if (null != args.NewValue)
InitializeKinectServices(KinectSensorManager, args.NewValue);
}
// Kinect enabled apps should customize which Kinect services it initializes here.
private void InitializeKinectServices(
KinectSensorManager kinectSensorManager,
KinectSensor sensor)
{
// Application should enable all streams first.
// configure the color stream
kinectSensorManager.ColorFormat =
ColorImageFormat.RgbResolution640x480Fps30;
kinectSensorManager.ColorStreamEnabled = true;
// configure the depth stream
kinectSensorManager.DepthStreamEnabled = true;
kinectSensorManager.TransformSmoothParameters =
new TransformSmoothParameters
{
Smoothing = 0.5f,
Correction = 0.5f,
Prediction = 0.5f,
JitterRadius = 0.05f,
MaxDeviationRadius = 0.04f
};
// configure the skeleton stream
sensor.SkeletonFrameReady += OnSkeletonFrameReady;
kinectSensorManager.SkeletonStreamEnabled = true;
}
// Kinect enabled apps should uninitialize all Kinect services that were initialized in InitializeKinectServices() here.
private void UninitializeKinectServices(KinectSensor sensor)
{
sensor.SkeletonFrameReady -= this.OnSkeletonFrameReady;
}
#endregion Kinect Discovery & Setup
You can then bind to the manager from your View as shown by the examples.
You make need to also set the DataContext, by putting the following into the constructor:
DataContext = this;