how to pass data between a dialogfragment to activity - xamarin.android

I want to send data from the dialogfragment to activity by one command inside the button .
//code in dialogfragment
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", "some_data");
editor.Apply();
second = new SecondActivity();
String myData = prefs.GetString("my_data", "");
second.txtView.Text = myData; // textview in secondactivity
Dismiss();

According to your description, your need to create Dialogfragment firstly in your project, and load layout in your DialogmentFragment.
public class DialogFragment1: DialogFragment
{
private TextView tv1;
private TextView tv2;
private Button btn1;
public static DialogFragment1 NewInstance(Bundle bundle)
{
DialogFragment1 fragment = new DialogFragment1();
fragment.Arguments = bundle;
return fragment;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.Signuplayout, container, false);
tv1 = view.FindViewById<TextView>(Resource.Id.textView1);
tv2= view.FindViewById<TextView>(Resource.Id.textView2);
btn1 = view.FindViewById<Button>(Resource.Id.button1);
btn1.Click += Btn1_Click;
return view;
}
private void Btn1_Click(object sender, EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", tv1.Text);
editor.Apply();
DialogFragment1 _exportFragment = (DialogFragment1)FragmentManager.FindFragmentByTag("Dialog Fragment");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
}
}
The signuplayout.xml:
<?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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:hint="first name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:hint="Pasword"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign up"
android:id="#+id/button1"/>
</LinearLayout>
Mainactivity.cs:
private Button btn1;
private Button btn2;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
btn1 = FindViewById<Button>(Resource.Id.button1);
btn2 = FindViewById<Button>(Resource.Id.button2);
btn1.Click += Btn1_Click;
btn2.Click += Btn2_Click;
}
private void Btn2_Click(object sender, System.EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
string myData = prefs.GetString("my_data", "");
}
private void Btn1_Click(object sender, System.EventArgs e)
{
FragmentTransaction transcation = FragmentManager.BeginTransaction();
DialogFragment1 signup = new DialogFragment1();
signup.Show(transcation, "Dialog Fragment");
}
<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">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" android:text="Sign up"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get data"
android:id="#+id/button2"/>
</LinearLayout>
Clicking first Button in MainLayout to display DialogFragment, then clicking Button in DialogFragment to pass data to activity, finally, clicking the second Button in MainLayout to get data.
This is one sample that you can take a look:
https://github.com/CherryBu/dialogapp
Update:
Adding one public method in Mainactivity.cs to display data:
public void getdata()
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
string myData = prefs.GetString("my_data", "");
Toast.MakeText(Application.Context,myData,ToastLength.Long).Show();
}
Then instantiate one Mainactivity, call getdata method in DialogFragment.cs:
static MainActivity mactivity;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.Signuplayout, container, false);
tv1 = view.FindViewById<TextView>(Resource.Id.textView1);
tv2= view.FindViewById<TextView>(Resource.Id.textView2);
btn1 = view.FindViewById<Button>(Resource.Id.button1);
btn1.Click += Btn1_Click;
mactivity = new MainActivity();
return view;
}
private void Btn1_Click(object sender, EventArgs e)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(Context);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("my_data", tv1.Text);
editor.Apply();
DialogFragment1 _exportFragment = (DialogFragment1)FragmentManager.FindFragmentByTag("Dialog Fragment");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
mactivity.getdata();
}

Related

RecyclerView in Fragment of ViewPager results in InflateException

I have a TabLayout with Fragments. In one of the Fragments, I want to add a RecyclerView. I have implemented the code for it and deployed it, but when I start the app I get the following error at tabLayout.SetupWithViewPager(viewPager):
Android.Views.InflateException: Binary XML file line #15: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.Button
and sometimes just
Android.Views.InflateException: Timeout exceeded getting exception details
I tried to copy the same code for the RecyclerView in a new Project but there just in the MainActivity and it worked. So I'm doing something else wrong...
My Code:
Main.axml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tablayout_navigation"
android:layout_width="match_parent"
app:tabTextColor="#ffffff"
app:tabSelectedTextColor="#08aeab"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="4dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="0dp" />
</LinearLayout>
Overview.axml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:minWidth="25px"
android:minHeight="25px">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
AppointmentListItem.axml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtName"
android:textColor="#fff"/>
</LinearLayout>
RecyclerAdapter.cs:
class RecyclerAdapter : RecyclerView.Adapter
{
private List<Appointment> mAppointments;
public RecyclerAdapter(List<Appointment> appointments)
{
mAppointments = appointments;
}
public class MyView : RecyclerView.ViewHolder
{
public View mMainView { get; set; }
public TextView mName { get; set; }
public MyView(View view) : base(view)
{
mMainView = view;
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View row = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.AppointmentListItem, parent, false);
TextView txtName = row.FindViewById<TextView>(Resource.Id.txtName);
MyView view = new MyView(row) { mName = txtName };
return view;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
MyView myHolder = holder as MyView;
myHolder.mName.Text = mAppointments[position].Name;
}
public override int ItemCount
{
get { return mAppointments.Count; }
}
}
OverviewFragment.cs
class OverviewFragment : Android.Support.V4.App.Fragment
{
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
private List<Appointment> mAppointments;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
View view = inflater.Inflate(Resource.Layout.Overview, container, false);
mAppointments = new List<Appointment>();
mAppointments.Add(new Appointment("Test1"));
mAppointments.Add(new Appointment("Test2"));
mAppointments.Add(new Appointment("Test3"));
mAppointments.Add(new Appointment("Test4"));
mRecyclerView = view.FindViewById<RecyclerView>(Resource.Id.recyclerView);
mLayoutManager = new LinearLayoutManager(view.Context);
mRecyclerView.SetLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(mAppointments);
mRecyclerView.SetAdapter(mAdapter);
return view;
}
}
MainActivity.cs:
public class MainActivity : AppCompatActivity
{
private TabLayout tabLayout;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
tabLayout = FindViewById<TabLayout>(Resource.Id.tablayout_navigation);
ViewPager viewPager = FindViewById<ViewPager>(Resource.Id.pager);
SetupViewPager(viewPager);
tabLayout.SetupWithViewPager(viewPager);
}
private void SetupViewPager(ViewPager viewPager)
{
viewPager.OffscreenPageLimit = 3;
PageAdapter adapter = new PageAdapter(SupportFragmentManager);
adapter.AddFragment(new OverviewFragment(), Resources.GetString(Resource.String.overview));
adapter.AddFragment(new CalendarFragment(), Resources.GetString(Resource.String.calendar));
adapter.AddFragment(new SharesFragment(), Resources.GetString(Resource.String.share));
viewPager.Adapter = adapter;
}
}

Fragment Navigation using map 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

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";
...

Which is the best widget to display dynamic table with data in Xamarin.Android?

I have to display the following table:
So I want to know what is the best widget to use for the table. I want the table to be dynamic I mean if I choose some other group from the dropdown the number of items in the table to increase or to decrease and the total price to change depending on what I have in column price. What widget is the best widget to achieve that?
RecyclerView is the best UI control to achieve it. Because RecyclerView is Adapter pattern, so you can use the adapter to achieve dynamic what you have said.
I want the table to be dynamic I mean if I choose some other group from the dropdown the number of items in the table to increase or to decrease and the total price to change depending on what I have in column price
I have made a demo for you, you can test it and do some changes for your project:
Three .axml files:
Main.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group1"/>
<Button
android:id="#+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group2"/>
<Button
android:id="#+id/bt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="group3"
/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
item_layout, every item's layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:textSize="30dp"
android:layout_height="wrap_content" />
</LinearLayout>
item_layout, total price's layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/foot_tv"
android:gravity="end"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity:
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using System.Collections.Generic;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Content;
namespace RecycleTest
{
[Activity(Label = "RecycleTest", MainLauncher = true)]
public class MainActivity : Activity
{
RecyclerView mRecyclerView;
MyAdapter adapter;
Button bt1, bt2, bt3;
List<double> list1, list2, list3;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
initView();
initData();
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.rv);
mRecyclerView.SetLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this, list1);
mRecyclerView.SetAdapter(adapter);
}
private void initData()
{
list1 = new List<double>();
list2 = new List<double>();
list3 = new List<double>();
list1.Add(1.1);
list1.Add(1.2);
list1.Add(1.3);
list2.Add(2.1);
list2.Add(2.2);
list2.Add(2.3);
list2.Add(2.4);
list3.Add(3.1);
list3.Add(3.2);
list3.Add(3.3);
list3.Add(3.4);
list3.Add(3.5);
}
public void initView() {
bt1 = FindViewById<Button>(Resource.Id.bt1);
bt2 = FindViewById<Button>(Resource.Id.bt2);
bt3 = FindViewById<Button>(Resource.Id.bt3);
bt1.Click += Bt1_Click;
bt2.Click += Bt2_Click;
bt3.Click += Bt3_Click;
}
private void Bt3_Click(object sender, System.EventArgs e)
{
adapter.change(list3);
}
private void Bt2_Click(object sender, System.EventArgs e)
{
adapter.change(list2);
}
private void Bt1_Click(object sender, System.EventArgs e)
{
adapter.change(list1);
}
}
class MyViewHolder : RecyclerView.ViewHolder
{
public TextView mtv;
public MyViewHolder(View itemView): base(itemView)
{
mtv = itemView.FindViewById<TextView>(Resource.Id.item_tv);
}
}
class MyFootViewHolder : RecyclerView.ViewHolder
{
public TextView mtv;
public MyFootViewHolder(View itemView):base(itemView)
{
mtv = itemView.FindViewById<TextView>(Resource.Id.foot_tv);
}
}
class MyAdapter :RecyclerView.Adapter{
Context mContext;
List<double> mList=new List<double>();
public override int ItemCount => mList.Count + 1;
public MyAdapter(Context context, List<Double> list)
{
this.mContext = context;
this.mList.AddRange(list);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (GetItemViewType(position) == 0)
{
((MyViewHolder)holder).mtv.Text=(mList[position].ToString());
}
else
{
double price = 0;
for (int i = 0; i < mList.Count; i++)
{
price += mList[i];
}
((MyFootViewHolder)holder).mtv.Text=price + "";
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
RecyclerView.ViewHolder holder;
if (viewType == 0)
{
holder = new MyViewHolder(LayoutInflater.From(mContext).Inflate(Resource.Layout.item_layout, parent, false));
}
else
{
holder = new MyFootViewHolder(LayoutInflater.From(mContext).Inflate(Resource.Layout.foot_layout, parent, false));
}
return holder;
}
public override int GetItemViewType(int position)
{
int type;
if (position != mList.Count)
{
type = 0;
}
else
{
type = 1;
}
return type;
}
public void change(List<Double> list1)
{
mList.Clear();
mList.AddRange(list1);
NotifyDataSetChanged();
}
}
}

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.

Resources