Fragment Navigation using map Xamarin Android - xamarin.android

The problem I'm getting is that when I navigate through the Application and when I first initialize the fragment containing map, it initializes nicely but when I navigate to different fragments and again come back to the fragment containing map it gives an error on initializing the 'view object', the error screenshot is attached below. Please help me out.
Main Activity Code
DrawerLayout drawerLayout;
NavigationView navigationView;
IMenuItem previousItem;
TextView UserNameTxt;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);
}
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
//Set hamburger items menu
SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
//setup navigation view
navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
var headerview = navigationView.GetHeaderView(0);
UserNameTxt = headerview.FindViewById<TextView>(Resource.Id.UserNameTxt);
UserNameTxt.Text = "Yousuf";
//handle navigation
navigationView.NavigationItemSelected += (sender, e) =>
{
if (previousItem != null)
previousItem.SetChecked(false);
navigationView.SetCheckedItem(e.MenuItem.ItemId);
previousItem = e.MenuItem;
switch (e.MenuItem.ItemId)
{
case Resource.Id.menuTracking:
ListItemClicked(2);
break;
case Resource.Id.menuHoldingRoutine:
ListItemClicked(0);
break;
case Resource.Id.menuCalendarEvent:
ListItemClicked(1);
break;
case Resource.Id.menuSettings:
StartActivity(typeof(SettingActivity));
break;
}
drawerLayout.CloseDrawers();
};
//if first time you will want to go ahead and click first item.
if (savedInstanceState == null)
{
navigationView.SetCheckedItem(Resource.Id.menuHoldingRoutine);
ListItemClicked(0);
}
}
int oldPosition = -1;
private void ListItemClicked(int position)
{
//this way we don't load twice, but you might want to modify this a bit.
if (position == oldPosition)
return;
oldPosition = position;
Fragment fragment = null;
switch (position)
{
case 0:
fragment = HoldingRoutineFragment.NewInstance();
//fragment = Fragment1.NewInstance();
break;
case 1:
fragment = CalendarEventFragment.NewInstance();
//fragment = Fragment2.NewInstance();
break;
case 2:
fragment = TrackingFragment.NewInstance();
break;
}
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
fragmentTx.Replace(Resource.Id.content_frame, fragment);
fragmentTx.AddToBackStack(null);
fragmentTx.Commit();
//SupportFragmentManager.BeginTransaction()
// .Replace(Resource.Id.content_frame, fragment)
// .Commit();
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
drawerLayout.OpenDrawer(GravityCompat.Start);
return true;
}
return base.OnOptionsItemSelected(item);
}
}
Xml code of MainActivity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/toolbar_layout">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_below="#id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu"
android:fitsSystemWindows="true" />
</android.support.v4.widget.DrawerLayout>
Tracking Fragment Code
using Android.OS;
using Android.Views;
using System;
using System.Collections.Generic;
using Android.Widget;
using Android.App;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using System.Timers;
using Android.Graphics;
using Android.Content;
namespace RoutineApp.Fragments
{
public class TrackingFragment : Fragment, IOnMapReadyCallback
{
private GoogleMap gMap;
private MapFragment mapFragment;
private LatLng oldposition;
private MarkerOptions markerOptions;
private Marker marker;
private Timer timer;
private int timercount = 0;
private Button BtnUp, BtnDown, BtnRight, BtnLeft, BtnDirection;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public static TrackingFragment NewInstance()
{
var frag1 = new TrackingFragment { Arguments = new Bundle() };
return frag1;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.tracking, container, false);
mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.TrackingMap);
mapFragment.GetMapAsync(this);
BtnUp = view.FindViewById<Button>(Resource.Id.Up_btn);
BtnDown = view.FindViewById<Button>(Resource.Id.Down_btn);
BtnLeft = view.FindViewById<Button>(Resource.Id.Left_btn);
BtnRight = view.FindViewById<Button>(Resource.Id.Right_btn);
BtnDirection = view.FindViewById<Button>(Resource.Id.Direction_btn);
return view;
}
public void OnMapReady(GoogleMap googleMap)
{
gMap = googleMap;
gMap.UiSettings.SetAllGesturesEnabled(true);
gMap.UiSettings.ZoomControlsEnabled = true;
gMap.UiSettings.CompassEnabled = true;
gMap.UiSettings.MyLocationButtonEnabled = true;
LatLng latLng = new LatLng(24.9288, 67.0402);
oldposition = latLng;
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latLng, 19);
gMap.MoveCamera(camera);
markerOptions = new MarkerOptions()
.SetPosition(latLng)
.SetTitle("Current Position")
.Draggable(true);
marker = gMap.AddMarker(markerOptions);
BtnUp.Click += BtnUp_Click;
BtnDown.Click += BtnDown_Click;
BtnLeft.Click += BtnLeft_Click;
BtnRight.Click += BtnRight_Click;
BtnDirection.Click += BtnDirection_Click;
//gmaps.MarkerClick += Gmaps_MarkerClick;
gMap.MarkerDragEnd += GMap_MarkerDragEnd;
}
private void BtnDirection_Click(object sender, EventArgs e)
{
var intent = new Intent(this.Activity, typeof(GoogleMapDirectionsActivity));
StartActivity(intent);
}
private void MarkerSetting(LatLng newlatlng, LatLng oldlatlng)
{
markerOptions = new MarkerOptions()
.SetPosition(newlatlng)
.SetTitle("Current Position")
.Draggable(true);
marker = gMap.AddMarker(markerOptions);
PolylineOptions line = new PolylineOptions().Add(newlatlng).Add(oldlatlng).InvokeColor(Color.Red);
Polyline polyline = gMap.AddPolyline(line);
oldposition = newlatlng;
}
private void BtnRight_Click(object sender, EventArgs e)
{
if (marker != null)
{
marker.Remove();
}
timercount = 0;
LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
newposition.Longitude = newposition.Longitude + 0.00001;
MarkerSetting(newposition, oldposition);
}
private void BtnLeft_Click(object sender, EventArgs e)
{
if (marker != null)
{
marker.Remove();
}
timercount = 0;
LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
newposition.Longitude = newposition.Longitude - 0.00001;
MarkerSetting(newposition, oldposition);
}
private void BtnDown_Click(object sender, EventArgs e)
{
if (marker != null)
{
marker.Remove();
}
timercount = 0;
LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
newposition.Latitude = newposition.Latitude - 0.00001;
MarkerSetting(newposition, oldposition);
}
private void BtnUp_Click(object sender, EventArgs e)
{
if (marker != null)
{
marker.Remove();
}
timercount = 0;
LatLng newposition = new LatLng(oldposition.Latitude, oldposition.Longitude);
newposition.Latitude = newposition.Latitude + 0.00001;
MarkerSetting(newposition, oldposition);
}
private void GMap_MarkerDragEnd(object sender, GoogleMap.MarkerDragEndEventArgs e)
{
timercount = 0;
LatLng newpositon = e.Marker.Position;
PolylineOptions line = new PolylineOptions().Add(newpositon).Add(oldposition).InvokeColor(Color.Red);
Polyline polyline = gMap.AddPolyline(line);
oldposition = newpositon;
}
public override void OnResume()
{
base.OnResume();
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (timercount < 10)
{
timercount++;
}
else
{
Activity.RunOnUiThread(() =>
{
CreateCircle();
});
}
}
private void CreateCircle()
{
CircleOptions circle = new CircleOptions();
circle.InvokeCenter(oldposition);
circle.InvokeRadius(1);
circle.InvokeStrokeColor(Color.Blue);
circle.InvokeFillColor(Color.LightSkyBlue);
gMap.AddCircle(circle);
timercount = 0;
}
}
}
Xml Code for the Tracking Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/super_map_container">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map_container"
android:weightSum="100">
<fragment
android:id="#+id/TrackingMap"
android:layout_height="0dp"
android:layout_width="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_weight="90" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10"
android:weightSum="10">
<Button
android:id="#+id/Up_btn"
android:layout_height="match_parent"
android:layout_width="20dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#A11"
android:layout_weight="2" />
<Button
android:id="#+id/Down_btn"
android:layout_height="match_parent"
android:layout_width="20dp"
android:layout_marginRight="10dp"
android:background="#B22"
android:layout_weight="2" />
<Button
android:id="#+id/Left_btn"
android:layout_height="match_parent"
android:layout_width="20dp"
android:layout_marginRight="10dp"
android:background="#C33"
android:layout_weight="2" />
<Button
android:id="#+id/Right_btn"
android:layout_height="match_parent"
android:layout_width="20dp"
android:layout_marginRight="10dp"
android:background="#D44"
android:layout_weight="2" />
<Button
android:id="#+id/Direction_btn"
android:layout_height="match_parent"
android:layout_width="20dp"
android:layout_marginRight="10dp"
android:background="#E55"
android:layout_weight="2" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
Error Screen Shot

Change your fragment code to this in your tracking fragment and try again :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="90"
class="com.google.android.gms.maps.MapFragment" />
If it doesn't work kindly revert

Related

ProgressBar stops spinning at some point while loading data inside activity (Xamarin.Android)

I have the following screen:
When I click on Ponentes ImageButton, ProgressBar appears while the data inside Ponentes activity is loading. The problem is that it stops spinning at some point. What may cause the issue and how can I fix it?
Here is the ProgressBar in the Ponentes axml:
<ProgressBar
android:id = "#+id/loadingSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:gravity="center"/>
Here is the OnCreate method of Ponentes Activity:
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.SpeakersActivity);
Android.Widget.Toolbar toolbar = FindViewById<Android.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.NavigationOnClick += delegate
{
this.OnBackPressed();
};
loadingSpinner = FindViewById<ProgressBar>(Resource.Id.loadingSpinner);
loadingSpinner.Visibility = ViewStates.Visible;
await Task.Run(() =>
{
//get all the speakers from the db
allSpeakers = DatabaseHelper.GetAllFromTable<Speaker>("speakers.db");
//get only the international spakers
internationalSpeakers = allSpeakers.Where(x => x.Nationality.Equals("international")).ToList();
//get only the national speakers
nationalSpeakers = allSpeakers.Where(x => x.Nationality.Equals("national")).ToList();
RunOnUiThread(() =>
{
speakersRecyclerView = FindViewById<RecyclerView>(Resource.Id.speakersRecyclerView);
speakersLayoutManager = new LinearLayoutManager(this);
speakersRecyclerView.SetLayoutManager(speakersLayoutManager);
speakersAdapter = new SpeakersAdapter(internationalSpeakers);
speakersAdapter.ItemClick += OnItemClick;
speakersRecyclerView.SetAdapter(speakersAdapter);
loadingSpinner.Visibility = ViewStates.Gone;
});
});
internationalSpeakersTextView = FindViewById<TextView>(Resource.Id.internationalSpeakersTextView);
internationalSpeakersTextView.Click += delegate
{
//change TextViews's style when selected/not-selected
internationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_selected);
nationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_unselected);
LoadSpeakers(internationalSpeakers);
};
nationalSpeakersTextView = FindViewById<TextView>(Resource.Id.nationalSpeakersTextView);
nationalSpeakersTextView.Click += delegate
{
//change TextViews's style when selected/not-selected
nationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_selected);
internationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_unselected);
LoadSpeakers(nationalSpeakers);
};
}
If you want I can paste you the entire Ponentes Activity
SpeakersActivity.cs :
[Activity(Label = "SpeakersActivity", ScreenOrientation = ScreenOrientation.Portrait)]
public class SpeakersActivity : BaseActivity
{
TextView internationalSpeakersTextView;
TextView nationalSpeakersTextView;
RecyclerView speakersRecyclerView;
// Layout manager that lays out each card in the RecyclerView:
RecyclerView.LayoutManager speakersLayoutManager;
// Adapter that accesses the data set (speakers):
SpeakersAdapter speakersAdapter;
/// <summary>
/// List that contains all the speakers
/// </summary>
List<Speaker> allSpeakers;
/// <summary>
/// List that contains the international speakers
/// </summary>
List<Speaker> internationalSpeakers;
/// <summary>
/// List that contains the national speakers
/// </summary>
List<Speaker> nationalSpeakers;
ProgressBar loadingSpinner;
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.SpeakersActivity);
Android.Widget.Toolbar toolbar = FindViewById<Android.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.NavigationOnClick += delegate
{
this.OnBackPressed();
};
loadingSpinner = FindViewById<ProgressBar>(Resource.Id.loadingSpinner);
loadingSpinner.Visibility = ViewStates.Visible;
await Task.Run(() =>
{
//get all the speakers from the db
allSpeakers = GetAllSpeakers();
//get only the international spakers
internationalSpeakers = allSpeakers.Where(x => x.Nationality.Equals("international")).ToList();
//get only the national speakers
nationalSpeakers = allSpeakers.Where(x => x.Nationality.Equals("national")).ToList();
RunOnUiThread(() =>
{
speakersRecyclerView = FindViewById<RecyclerView>(Resource.Id.speakersRecyclerView);
speakersLayoutManager = new LinearLayoutManager(this);
speakersRecyclerView.SetLayoutManager(speakersLayoutManager);
LoadSpeakers(internationalSpeakers);
loadingSpinner.Visibility = ViewStates.Gone;
});
});
internationalSpeakersTextView = FindViewById<TextView>(Resource.Id.internationalSpeakersTextView);
internationalSpeakersTextView.Click += delegate
{
//change TextViews's style when selected/not-selected
internationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_selected);
nationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_unselected);
LoadSpeakers(internationalSpeakers);
};
nationalSpeakersTextView = FindViewById<TextView>(Resource.Id.nationalSpeakersTextView);
nationalSpeakersTextView.Click += delegate
{
//change TextViews's style when selected/not-selected
nationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_selected);
internationalSpeakersTextView.SetBackgroundResource(Resource.Drawable.textView_unselected);
LoadSpeakers(nationalSpeakers);
};
}
/// <summary>
/// Load speakers inside activity
/// </summary>
/// <param name="speakers">speakers</param>
private void LoadSpeakers(List<Speaker> speakers)
{
speakersAdapter = new SpeakersAdapter(speakers);
speakersAdapter.ItemClick += OnItemClick;
speakersRecyclerView.SetAdapter(speakersAdapter);
}
private void OnItemClick(object sender, string speakerResumeUrl)
{
var speakerDetailsActivity = new Intent(this, typeof(SpeakerDetailsActivity));
speakerDetailsActivity.PutExtra("speakerResumeUrl", speakerResumeUrl);
StartActivity(speakerDetailsActivity);
}
public override void OnBackPressed()
{
StartActivity(typeof(CongressActivity));
Finish();
}
private List<Speaker> GetAllSpeakers()
{
System.Threading.Thread.Sleep(4000);
List<Speaker> speakers = new List<Speaker>();
speakers.Add(new Speaker { Photo = "https://i.imgur.com/DDH2Ckk.png", Name = "Anne-Maree Keenan", Resume = "https://51congresopodologia.com/?page_id=4004", Nationality = "international" });
speakers.Add(new Speaker { Photo = "https://i.imgur.com/DDH2Ckk.png", Name = "Anthony Redmond", Resume = "https://51congresopodologia.com/?page_id=4004", Nationality = "international" });
speakers.Add(new Speaker { Photo = "https://i.imgur.com/DDH2Ckk.png", Name = "Chris Nester", Resume = "https://51congresopodologia.com/?page_id=4004", Nationality = "national" });
speakers.Add(new Speaker { Photo = "https://i.imgur.com/DDH2Ckk.png", Name = "Amol Saxena", Resume = "https://51congresopodologia.com/?page_id=4004", Nationality = "international" });
return speakers;
}
}
SpeakersActivity.axml :
<?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"
android:weightSum="100">
<Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="#color/appColor"
android:navigationIcon="#drawable/ic_toolbar_back_button">
<TextView
android:text="Ponentes"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"/>
</Toolbar>
<LinearLayout
android:orientation="horizontal"
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="0dp"
android:weightSum="100"
android:layout_weight="10">
<TextView
android:text="Internacionales"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/internationalSpeakersTextView"
android:layout_weight="50"
android:gravity="center"
android:background="#drawable/textView_selected"/>
<TextView
android:text="Nacionales"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/nationalSpeakersTextView"
android:layout_weight="50"
android:gravity="center"
android:background="#drawable/textView_unselected"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/speakersRecyclerView"
android:layout_weight="90"/>
<ProgressBar
android:id = "#+id/loadingSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:gravity="center"/>
<!--android:indeterminateDrawable="#drawable/animdraw"-->
</LinearLayout>
SpeakersAdapter.cs :
public class SpeakersAdapter : RecyclerView.Adapter
{
public event EventHandler<string> ItemClick;
public List<Speaker> listOfSpeakers;
public SpeakersAdapter(List<Speaker> speakers)
{
listOfSpeakers = speakers;
}
public override int ItemCount
{
get { return listOfSpeakers.Count; }
}
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, listOfSpeakers[position].Resume);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
SpeakerViewHolder vh = holder as SpeakerViewHolder;
var imageBitmap = GetImageBitmapFromUrl(listOfSpeakers[position].Photo);
vh.speakerPhotoImageView.SetImageBitmap(imageBitmap);
vh.speakerNameTextView.Text = listOfSpeakers[position].Name;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.SpeakerCardView, parent, false);
SpeakerViewHolder vh = new SpeakerViewHolder(itemView, OnClick);
return vh;
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
}
SpeakerViewHolder.cs :
public class SpeakerViewHolder : RecyclerView.ViewHolder
{
public ImageView speakerPhotoImageView { get; private set; }
public TextView speakerNameTextView { get; private set; }
public TextView speakerResumeTextView { get; private set; }
// Get references to the views defined in the CardView layout.
public SpeakerViewHolder(View itemView, Action<int> listener)
: base(itemView)
{
// Locate and cache view references:
speakerPhotoImageView = itemView.FindViewById<ImageView>(Resource.Id.speakerPhotoImageView);
speakerNameTextView = itemView.FindViewById<TextView>(Resource.Id.speakerNameTextView);
// Detect user clicks on the item view and report which item
// was clicked (by layout position) to the listener:
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
}
textView_selected.xml :
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#6495ED" />
<stroke
android:width="1dp"
android:color="#DCDCDC" />
</shape>
textView_unselected.xml :
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#DCDCDC" />
</shape>
I've put System.Threading.Thread.Sleep(4000); in the GetAllSpeakers method in SpeakersActivity in order to imitate the delay when I get the records from a real database. Tell me if I am missing some file.

Can't set the textview in the navigation drawer using navigation view in main activity. Xamarin Android

This is the main activity where I am setting all the icons, menu, drawer and my navigation view. Here I set another view by inflating nav_header into the view and set the textview but I still can't seem to change the textview in the navigation drawer.
MainActivity
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Support.V4.Widget;
using Android.Views;
using RoutineApp.Fragments;
using Android.Support.V7.App;
using Android.Support.V4.View;
using Android.Support.Design.Widget;
using Android.Widget;
using Android.Content;
namespace RoutineApp
{
[Activity(Label = "#string/app_name", MainLauncher = true, LaunchMode = LaunchMode.SingleTop)]
public class MainActivity : AppCompatActivity
{
DrawerLayout drawerLayout;
NavigationView navigationView;
IMenuItem previousItem;
TextView UserNameTxt;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);
}
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
LayoutInflater inflater = (LayoutInflater)GetSystemService(Context.LayoutInflaterService);
View view = inflater.Inflate(Resource.Layout.nav_header, null);
UserNameTxt = view.FindViewById<TextView>(Resource.Id.UserNameTxt);
UserNameTxt.Text = "Yousuf";
navigationView.NavigationItemSelected += (sender, e) =>
{
if (previousItem != null)
previousItem.SetChecked(false);
navigationView.SetCheckedItem(e.MenuItem.ItemId);
previousItem = e.MenuItem;
switch (e.MenuItem.ItemId)
{
case Resource.Id.nav_home_1:
ListItemClicked(0);
break;
case Resource.Id.nav_home_2:
ListItemClicked(1);
break;
}
drawerLayout.CloseDrawers();
};
if (savedInstanceState == null)
{
navigationView.SetCheckedItem(Resource.Id.nav_home_1);
ListItemClicked(0);
}
}
int oldPosition = -1;
private void ListItemClicked(int position)
{
if (position == oldPosition)
return;
oldPosition = position;
Fragment fragment = null;
switch (position)
{
case 0:
fragment = Fragment1.NewInstance();
break;
}
FragmentTransaction fragmentTx = this.FragmentManager.BeginTransaction();
fragmentTx.Replace(Resource.Id.content_frame, fragment);
fragmentTx.AddToBackStack(null);
fragmentTx.Commit();
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
drawerLayout.OpenDrawer(GravityCompat.Start);
return true;
}
return base.OnOptionsItemSelected(item);
}
}
}
This is the main layout axml where the navigation and drawer are set the header is called in the navigation.
main.axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
app:layout_scrollFlags="scroll|enterAlways" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar_layout" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu" />
</android.support.v4.widget.DrawerLayout>
This is my the nav_header which I have called in the navigation view, which contains the textview which I'm trying to change on main activity.
nav_header.axml
<TextView
android:id="#+id/UserNameTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Username"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
</LinearLayout>
The name doesn't change, please help.
You use LayoutInflator to inflate a view from nav_header, which means you created a total new View from nav_header.xml and changed it's sub textview's text and didn't use this new view in your activity. Thus the text of your original activity won't change.
solution:
Modify your activity codes like this:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.main);
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
SetSupportActionBar(toolbar);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);
}
drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
//LayoutInflater inflater = (LayoutInflater)GetSystemService(Context.LayoutInflaterService);
//View view = inflater.Inflate(Resource.Layout.nav_header, null);
//UserNameTxt = view.FindViewById<TextView>(Resource.Id.UserNameTxt);
//UserNameTxt.Text = "Yousuf";
LinearLayout header=(LinearLayout)navigationView.GetHeaderView(0);
UserNameTxt = header.FindViewById<TextView>(Resource.Id.UserNameTxt);
UserNameTxt.Text = "Yousuf";
...

Create AlertDialog with ProgressBar in it. (Xamarin.Android)

I have created the following alert dialog and progressbar:
LayoutInflater layoutInflater = LayoutInflater.From(this);
View progressDialogBox = layoutInflater.Inflate(Resource.Layout.progress_dialog_box, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.SetView(progressDialogBox);
var progressBar1 = progressDialogBox.FindViewById<ProgressBar>(Resource.Id.progressBar1);
progressBar1.Max = 100;
progressBar1.Progress = 0;
Dialog dialog = alertDialogBuilder.Create();
dialog.Show();
And I make it increase every 2 seconds
System.Threading.Thread.Sleep(2000);
progressBar1.IncrementProgressBy(25);
System.Threading.Thread.Sleep(2000);
progressBar1.IncrementProgressBy(25);
System.Threading.Thread.Sleep(2000);
progressBar1.IncrementProgressBy(25);
System.Threading.Thread.Sleep(2000);
progressBar1.IncrementProgressBy(25);
progress_dialog_box.axml contains that code:
<?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">
<TextView
android:text="Getting data..."
android:layout_gravity="center"
android:paddingTop="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar1" />
</LinearLayout>
But when I run the application the ProgressBar stays at 0. How can I make it progress?
But when I run the application the ProgressBar stays at 0.
It is 100 instead of 0. progressBar1.IncrementProgressBy(25); will be called before the dialog shows(I haven't found why the process have been done before the dialog shows, I will update my solution if I found).
Here is a simple:
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
LayoutInflater layoutInflater = LayoutInflater.From(this);
View progressDialogBox = layoutInflater.Inflate(Resource.Layout.progress_dialog_box, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.SetView(progressDialogBox);
var progressBar1 = progressDialogBox.FindViewById<ProgressBar>(Resource.Id.progressBar1);
progressBar1.Max = 100;
progressBar1.Progress = 0;
Dialog dialog = alertDialogBuilder.Create();
dialog.Show();
UpdatePB uptask = new UpdatePB(this, progressBar1);
uptask.Execute(100);
}
public class UpdatePB : AsyncTask<int, int, string>
{
Activity mcontext;
ProgressBar mpb;
public UpdatePB(Activity context, ProgressBar pb)
{
this.mcontext = context;
this.mpb = pb;
}
protected override string RunInBackground(params int[] #params)
{
// TODO Auto-generated method stub
for (int i = 1; i <= 4; i++)
{
try
{
System.Threading.Thread.Sleep(3000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
Android.Util.Log.Error("lv", e.Message);
}
mpb.IncrementProgressBy(25);
PublishProgress(i * 25);
}
return "finish";
}
protected override void OnProgressUpdate(params int[] values)
{
Android.Util.Log.Error("lv==", values[0] + "");
}
protected override void OnPostExecute(string result)
{
mcontext.Title = result;
}
}
}
And change your ProgressBar's width to match_parent, it will be better.

Xamarin.Android NavigationTabStrip

I want to implement the NavigationTabStrip (https://github.com/martijn00/NavigationTabStripXamarin) to my app, but I don't know how. I've seen also the original project, but I'm new in this world. Has anyone a project to help me to implement this? Or is there anyone that knows how to do that? I'm trying to create a TabLayout in material design.
The Easiest way to do it would be like this :
http://camposha.info/source/xamarin-android-swipe-tabs-viewpager-fragments-images-actionbartabs/
http://www.c-sharpcorner.com/article/creating-sliding-tab-layout-interface-using-xamarin-android-using-visual-studio/
The code is in xamarin so it would be an easy implementation for you!
Goodluck!
UPDATE:
The code for your activities Axml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/MyTheme"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
/>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Code for your Activities cs file:
public class GoogleMapsActivity : AppCompatActivity
{
private Fragment MapsFragment;
private Fragment ListFragment;
private TabLayout allTabs;
FragmentManager fm;
FragmentTransaction ft;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.your_activity);
bindAllWidgets();
setupTabLayout();
setUpToolbar();
}
void setUpToolbar()
{
#region "Tool bar"
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.SetTitleTextColor(ResourcesCompat.GetColor(Resources, Resource.Color.colorRedText, null));
Drawable upArrow = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.abc_ic_ab_back_mtrl_am_alpha, null);
upArrow.SetColorFilter(Color.ParseColor(Resources.GetString(Resource.Color.colorRedText)), PorterDuff.Mode.SrcAtop);
SetSupportActionBar(toolbar);
SupportActionBar.Title = Resources.GetString(Resource.String.toolbar_title_dhl_service_points);
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeAsUpIndicator(upArrow);
#endregion
}
private void setupTabLayout()
{
allTabs.AddTab(allTabs.NewTab().SetText(Resources.GetString(Resource.String.google_maps_page_title_map)), true);
allTabs.AddTab(allTabs.NewTab().SetText(Resources.GetString(Resource.String.google_maps_page_title_list)));
}
private void bindAllWidgets()
{
allTabs = FindViewById<TabLayout>(Resource.Id.tabs);
allTabs.TabSelected += AllTabs_TabSelected;
}
private void AllTabs_TabSelected(object sender, TabSelectedEventArgs e)
{
var tab = e.Tab;
setCurrentTabFragment(tab.Position);
}
public void replaceFragment(Fragment fragment)
{
fm = FragmentManager;
ft = fm.BeginTransaction();
if (fragment == MapsFragment)
{
if (MapsFragment == null)
{
MapsFragment = new PoSLocationMapView(this);
ft.Add(Resource.Id.frame_container, MapsFragment, "MapsFragment");
}
else
{
ft.Detach(FragmentManager.FindFragmentByTag("ListFragment"));
ft.Attach(MapsFragment);
}
}
else if (fragment == ListFragment)
{
if (ListFragment == null)
{
ListFragment = new ServicePointDHLList(this);
ft.Add(Resource.Id.frame_container, ListFragment, "ListFragment");
}
else
{
ft.Detach(FragmentManager.FindFragmentByTag("MapsFragment"));
ft.Attach(ListFragment);
}
}
ft.SetTransition(FragmentTransit.FragmentOpen);
ft.Commit();
}
private void setCurrentTabFragment(int tabPosition)
{
switch (tabPosition)
{
case 0:
replaceFragment(MapsFragment);
break;
case 1:
replaceFragment(ListFragment);
break;
}
}
}
Try this library it is more clearly.
https://github.com/ahoefling/TabStrip/blob/master/README.md

How to overlay google place auto complete fragment in map fragment in xamarin android?

I am working in Xamarin android, i want to show google place autocomplete fragment in google map fragment, am using this below code but it getting error, anyone can help to solve this?
Android.Views.InflateException: Binary XML file line #1: Error
inflating class fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/googlemap"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment">
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" />
</fragment>
</LinearLayout>
namespace test
{
[Activity(Label = "CommuteX", MainLauncher = true, Icon = "#mipmap/icon", Theme = "#android:style/Theme.Holo.Light.NoActionBar.Fullscreen")]
public class MainActivity : FragmentActivity, IOnMapReadyCallback, IPlaceSelectionListener, IOnConnectionFailedListener
{
private GoogleMap GMap;
public void OnConnectionFailed(ConnectionResult result)
{
throw new NotImplementedException();
}
public void OnError(Statuses status)
{
Log.Info("xamarin", "An error occurred: " + status);
}
public void OnMapReady(GoogleMap googleMap)
{
this.GMap = googleMap;
LatLng latlng = new LatLng(Convert.ToDouble(12.733027), Convert.ToDouble(77.83016));
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 15);
GMap.MoveCamera(camera);
MarkerOptions options = new MarkerOptions().SetPosition(latlng).SetTitle("Hosur");
GMap.AddMarker(options);
}
public void OnPlaceSelected(IPlace place)
{
var placeadd = place.AddressFormatted;
var placename = place.NameFormatted;
var namadd = placename + "," + placeadd;
var latlng = place.LatLng;
Log.Info("xamarin", "Place: " + namadd);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
SetUpMap();
var mGoogleApiClient = new GoogleApiClient
.Builder(this)
.AddApi(PlacesClass.GEO_DATA_API)
.AddApi(PlacesClass.PLACE_DETECTION_API)
.EnableAutoManage(this, this)
.Build();
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)FragmentManager.FindFragmentById(Resource.Id.place_autocomplete_fragment);
autocompleteFragment.SetOnPlaceSelectedListener(this);
}
private void SetUpMap()
{
if (GMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
}
}

Resources