Passing strings from an Activity to a DialogFragment - c#

in my activity I have this:
public class MainActivity : Activity
{
RelativeLayout mRelativeLayout;
Button mButton;
private Button mBtnSignUp;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mRelativeLayout = FindViewById<RelativeLayout>(Resource.Id.mainView);
mButton = FindViewById<Button>(Resource.Id.btnLogin);
mButton.Click += mButton_Click;
mRelativeLayout.Click += mRelativeLayout_Click;
mBtnSignUp = FindViewById<Button> (Resource.Id.button1);
mBtnSignUp.Click += (object sender, EventArgs e) =>
{
//Pull up dialog
FragmentTransaction transaction = FragmentManager.BeginTransaction();
dialog_SignUp signUpDialog = new dialog_SignUp();
signUpDialog.Show(transaction, "dialog fragment");
signUpDialog.mOnSignUpComplete += signUpDialog_mOnSignUpComplete;
};
void signUpDialog_mOnSignUpComplete (object sender, OnSignUpEventArgs e)
{
Thread thread = new Thread (ActLikeARequest);
thread.Start ();
}
private void ActLikeARequest()
{
Thread.Sleep (3000);
}
And in the dialog I have:
public class OnSignUpEventArgs : EventArgs
{
private string mFirstName;
private string mEmail;
private string mPassword;
public string FirstName
{
get{ return mFirstName; }
set{ mFirstName=value;}
}
public string Email
{
get{ return mEmail; }
set{ mEmail=value;}
}
public string Password
{
get{ return mPassword; }
set{ mPassword=value;}
}
public OnSignUpEventArgs (string firstName, string email, string password) : base()
{
FirstName = firstName;
Email = email;
Password = password;
}
}
class dialog_SignUp:DialogFragment
{
private Button mBtnSignUp;
private EditText mFirstName;
private EditText mEmail;
private EditText mPassword;
public event EventHandler<OnSignUpEventArgs> mOnSignUpComplete;
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.dialog_sign_up, container, false);
mBtnSignUp = view.FindViewById<Button> (Resource.Id.btnDialogEmail);
mFirstName = view.FindViewById<EditText> (Resource.Id.txtFirstName);
mEmail = view.FindViewById<EditText> (Resource.Id.txtEmail);
mPassword = view.FindViewById<EditText> (Resource.Id.txtPassword);
mBtnSignUp.Click += mBtnSignUp_Click;
return view;
}
void mBtnSignUp_Click (object sender, EventArgs e)
{
//User has clicked the sign up button
mOnSignUpComplete.Invoke (this, new OnSignUpEventArgs(mFirstName.Text, mEmail.Text, mPassword.Text));
this.Dismiss ();
}
public override void OnActivityCreated (Bundle savedInstanceState)
{
Dialog.Window.RequestFeature (WindowFeatures.NoTitle); //Sets the title bar to invisible
base.OnActivityCreated (savedInstanceState);
Dialog.Window.Attributes.WindowAnimations = Resource.Style.dialog_animation; //Set the animation
}
}
The question is, how can I pass data(strings) from the activity into the dialog, so that when it is called, the TextViews get the data I'm passing?
Is it something to add in the actitity, but what?

i think you need to be able to accept a parameter in your dialog_signup.
class dialog_SignUp:DialogFragment
{
private Button mBtnSignUp;
private EditText mFirstName;
private EditText mEmail;
private EditText mPassword;
String parameter="";
public event EventHandler<OnSignUpEventArgs> mOnSignUpComplete;
public dialog_SignUp(String parameterIn){
parameter=parameterIn;
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.dialog_sign_up, container, false);
mBtnSignUp = view.FindViewById<Button> (Resource.Id.btnDialogEmail);
mFirstName = view.FindViewById<EditText> (Resource.Id.txtFirstName);
mFirstName.setText(parameter);
mEmail = view.FindViewById<EditText> (Resource.Id.txtEmail);
mPassword = view.FindViewById<EditText> (Resource.Id.txtPassword);
mBtnSignUp.Click += mBtnSignUp_Click;
return view;
}
then replace dialog_SignUp signUpDialog = new dialog_SignUp(); with dialog_SignUp signUpDialog = new dialog_SignUp(stringToSend);

Keep in mind that you can always use The Application class to define a variable there.
namespace YourNamespace
{
[Application]
public class App : Application
{
public ParseObject currentBusiness { get; set;}
public App (IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnCreate ()
{
base.OnCreate ();
currentBusiness = new ParseObject ("Business");
}
}
}
Then you can access it from evewhere in that way:
App _app = (App)Application.Context;
var curentBusiness = _app.currentBusiness;

You can use Property feature of Class.
Dialog Fragment Code
class Error : DialogFragment
{
public string getErrorMsg { get; set; } // this gets the message
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.Error, container, false);
TextView text = view.FindViewById<TextView>(Resource.Id.txtError);
text.Text = getErrorMsg; //here the message is set to the TextView
return view;
}
}
Calling Method
FragmentTransaction transaction = FragmentManager.BeginTransaction();
Error obj = new Error();
obj.Cancelable = false;
obj.getErrorMsg = passMyString; // in this line you send message to The Class
obj.Show(transaction, "error");

Related

PopBackStack from fragment back to previous listview not data not visible anymore xamarin.android

I have an activity en I start the frist fragment from that activity:
var fragment1 = new Fragment1();
var fragmentManager = SupportFragmentManager;
var ft = fragmentManager.BeginTransaction()
.SetCustomAnimations(Resource.Animation.abc_fade_in, Resource.Animation.abc_fade_out)
.AddToBackStack(nameof(Fragment1))
.Add(Resource.Id.content_frame, fragment1)
.Commit();
In Fragment1 I have a listview and I'm using an adapter to populate the list view. At first time load it works perfectly. I start Fragment2 from Fragment1 in with this code:
var fragment2 = new Fragment2();
var fragmentManager = SupportFragmentManager;
var ft = fragmentManager.BeginTransaction()
.SetCustomAnimations(Resource.Animation.abc_fade_in, Resource.Animation.abc_fade_out)
.AddToBackStack(nameof(Fragment2))
.Add(Resource.Id.content_frame, fragment2)
.Commit();
But when I navigate from Fragment1 to Fragment2 and call PopBackStack from Fragment2 to go back to Fragment1, the list view is totally blanc.
Here is my Fragment1 code:
public class Fragment1 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
base.OnViewCreated(view, savedInstanceState);
SetUpListView(view);
}
public void RefreshListView(List<Item> items)
{
if (View == null) return;
var listView = View.FindViewById<ListView>(Resource.Id.lv_items);
var adapter = listView.Adapter as ItemsListViewAdapter;
adapter.Items = items;
adapter.NotifyDataSetChanged();
}
private void SetUpListView(View view)
{
var adapter = new ItemsListViewAdapter(Activity);
var listView = view.FindViewById<ListView>(Resource.Id.lv_items);
listView.Adapter = adapter;
listView.ItemClick += ListView_ItemClick;
}
private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var fragment2 = new Fragment2();
var fragmentManager = Activity.SupportFragmentManager;
var ft = fragmentManager.BeginTransaction();
ft.Replace(Resource.Id.content_frame, fragment2);
ft.AddToBackStack(null);
ft.Commit();
}
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.items, container, false);
}
}
Here is my Fragment 2:
public class Fragment2 : Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
inflater.Inflate(Resource.Menu.shipments_search_menu, menu);
var searchItem = menu.FindItem(Resource.Id.action_search);
var searchView = (SearchView)searchItem.ActionView;
var expandListener = new OnActionExpandListener();
expandListener.Collapse += (s, e) =>
{
Activity.SupportFragmentManager.PopBackStack();//here I must go back to Fragment1
};
searchItem.SetOnActionExpandListener(expandListener);
searchView.QueryTextChange += SearchView_QueryTextChange;
base.OnCreateOptionsMenu(menu, inflater);
}
private void SearchView_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e)
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
HasOptionsMenu = true;
return inflater.Inflate(Resource.Layout.search_shipments, container, false);
}
}
Am i missing something? Any help would be apreciated.

OnScrollChanged doesn't get the RecyclerView parameters

I'm trying to implement this code here in my project:
The differences are that instead of a ScrollView I'm using a RecyclerView and that instead of having my RecyclerView directly in the Activity I have inside a fragment that sets the listener I need.
The problem is that while the OnScrollChanged(int l, int t, int oldl, int oldt) gets actually called everytime I scroll, the parameters it obtains are always 0 and I don't understand why, so ScrollChangedTarget doesn't work as intended.
This is the custom RecyclerView:
public class NotifyingScrollRecyclerView : RecyclerView
{
private Activity activity;
private View headerView;
private View footerView;
public delegate void ScrollChangedHandler(int l, int t, int oldl, int oldt, EventArgs e);
public event ScrollChangedHandler scrollChanged;
public EventArgs e = null;
//Enabling all required constructors
public NotifyingScrollRecyclerView(Context context) : base(context)
{
}
public NotifyingScrollRecyclerView(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public NotifyingScrollRecyclerView(IntPtr ptr, JniHandleOwnership ownership) : base(ptr, ownership)
{
}
public NotifyingScrollRecyclerView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
}
//This method attribute allows us to register the inbuilt OnScrollChanged event that fires when scrolling a ScrollView
[Android.Runtime.Register("onScrollChanged", "(IIII)V", "GetOnScrollChanged_IIIIHandler")]
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
base.OnScrollChanged(l, t, oldl, oldt);
scrollChanged(l, t, oldl, oldt, e);
}
}
//Set an event listener
public class ScrollViewChangedListener
{
private Activity activity;
private NotifyingScrollRecyclerView scrollView;
private Android.Support.V7.App.ActionBar actionBar;
private Drawable actionBarDrawable;
be changed
public ScrollViewChangedListener(Activity a, NotifyingScrollRecyclerView n)
{
n.scrollChanged += ScrollChangedTarget;
this.activity = a;
this.scrollView = n;
this.actionBar = ((UserPageActivity)a).SupportActionBar;
this.actionBarDrawable = a.GetDrawable(Resource.Drawable.actionbar_background);
this.actionBarDrawable.SetAlpha(0);
}
//Handle the changing of the scroll
public void ScrollChangedTarget(int l, int t, int oldl, int oldt, EventArgs e)
{
//You set the View you want to be your header as a header height, and then get it's height
int headerHeight = activity.FindViewById<ImageView>(Resource.Id.profilebanner).Height -
this.actionBar.Height;
float ratio = (float)Math.Min(Math.Max(t, 0), headerHeight) / headerHeight;
int newAlpha = (int)(ratio * 255);
this.actionBarDrawable.SetAlpha(newAlpha);
this.actionBar.SetBackgroundDrawable(this.actionBarDrawable);
}
}
This is the Activity which calls the fragment (it doesn't do anything in particular aside calling the fragment in this case):
[Activity(Label = "UserPageActivity")]
public class UserPageActivity : BaseActivity
{
protected override int LayoutResource => Resource.Layout.activity_user_page;
UserViewModel viewModel;
TextView username;
TextView usernameToolbar;
Button followButton;
ViewPager pager;
UserTabsAdapter adapter;
bool IsLoggedUser;
protected override void OnCreate(Bundle savedInstanceState)
{
IsLoggedUser = Intent.GetStringExtra("userId").Equals(LoginController.GetInstance().CurrentUser.Email);
base.OnCreate(savedInstanceState);
viewModel = new UserViewModel();
viewModel.UserLoaded += new UserViewModel.UserLoadedHandler(OnUserLoaded);
viewModel.LoadUserCommand.Execute(Intent.GetStringExtra("userId"));
username = FindViewById<TextView>(Resource.Id.profilename);
usernameToolbar = FindViewById<TextView>(Resource.Id.usernamePage);
followButton = FindViewById<Button>(Resource.Id.followButton);
username.Text = Intent.GetStringExtra("username");
usernameToolbar.Text = Intent.GetStringExtra("username");
adapter = new UserTabsAdapter(this, SupportFragmentManager);
pager = FindViewById<ViewPager>(Resource.Id.user_viewpager);
var tabs = FindViewById<TabLayout>(Resource.Id.tabs);
pager.Adapter = adapter;
tabs.SetupWithViewPager(pager);
pager.OffscreenPageLimit = 5;
pager.PageSelected += (sender, args) =>
{
var fragment = adapter.InstantiateItem(pager, args.Position) as IFragmentVisible;
fragment?.BecameVisible();
};
}
private void OnUserLoaded(bool loaded)
{
}
protected override void OnStart()
{
base.OnStart();
if (IsLoggedUser)
{
followButton.Visibility = ViewStates.Gone;
}
else
{
bool following;
if (LoginController.GetInstance().CurrentUser.FollowsUsers.ContainsKey(Intent.GetStringExtra("userId")))
{
followButton.Text = "Unfollow";
following = true;
}
else
{
followButton.Text = "Follow";
following = false;
}
followButton.Click += (object sender, EventArgs e) =>
{
followButton.Enabled = false;
if (following)
{
UserService service = ServiceLocator.Instance.Get<UserService>();
service.SetUser(LoginController.GetInstance().CurrentUser);
service.RemoveFollowsUserCommand.Execute(viewModel.LoadedUser.Email);
service.SetUser(viewModel.LoadedUser);
service.RemoveFollowedByUserCommand.Execute(LoginController.GetInstance().CurrentUser.Email);
followButton.Text = "Follow";
following = false;
}
else
{
UserService service = ServiceLocator.Instance.Get<UserService>();
service.SetUser(LoginController.GetInstance().CurrentUser);
service.AddFollowsUserCommand.Execute(viewModel.LoadedUser);
service.SetUser(viewModel.LoadedUser);
service.AddFollowedByUserCommand.Execute(LoginController.GetInstance().CurrentUser);
followButton.Text = "Unfollow";
following = true;
}
followButton.Enabled = true;
};
}
}
}
class UserTabsAdapter : FragmentStatePagerAdapter
{
string[] titles;
public override int Count => titles.Length;
public UserTabsAdapter(Context context, Android.Support.V4.App.FragmentManager fm) : base(fm)
{
titles = context.Resources.GetTextArray(Resource.Array.user_sections);
}
public override Java.Lang.ICharSequence GetPageTitleFormatted(int position) =>
new Java.Lang.String(titles[position]);
public override Android.Support.V4.App.Fragment GetItem(int position)
{
switch (position)
{
case 0: return UserContestsFragment.NewInstance();
case 1: return UserPartecipationsFragment.NewInstance();
case 2: return GlobalContestFragment.NewInstance();
case 3: return MessagesFragment.NewInstance();
}
return null;
}
public override int GetItemPosition(Java.Lang.Object frag) => PositionNone;
}
This is the fragment which setups the listener for the recyclerview:
public class UserContestsFragment : AbstractRefresherFadingToolbarFragment<Contest>
{
public static UserContestsFragment NewInstance() =>
new UserContestsFragment { Arguments = new Bundle() };
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
ContestViewModel viewModel = new ContestViewModel();
base.ViewModel = viewModel;
base.LoadItemsCommand = viewModel.LoadAllByCreatorUserCommand;
base.param = Activity.Intent.GetStringExtra("userId");
base.adapter = new ContestsAdapter(Activity, viewModel);
var view = base.OnCreateView(inflater, container, savedInstanceState);
ScrollViewChangedListener listener = new ScrollViewChangedListener(Activity, recyclerView);
return view;
}
And this is the abstract fragment needed by that fragment which is in charge of setting up the layout:
public abstract class AbstractRefresherFadingToolbarFragment<T> : Android.Support.V4.App.Fragment, IFragmentVisible
{
public ICollectionViewModel<T> ViewModel;
public ICommand LoadItemsCommand;
public object param; //parametro per il LoadItemsCommand
public ItemsAdapter<T> adapter;
public SwipeRefreshLayout refresher;
public ProgressBar progress;
public NotifyingScrollRecyclerView recyclerView;
//LruCache cache = new LruCache((int)(Runtime.GetRuntime().MaxMemory() / 4));
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.fragment_fading_toolbar, container, false);
recyclerView = view.FindViewById<NotifyingScrollRecyclerView>(Resource.Id.recyclerView);
//ScrollViewChangedListener listener = new ScrollViewChangedListener((UserPageActivity)Activity, recyclerView);
//adapter.cache = cache;
recyclerView.HasFixedSize = true;
recyclerView.SetAdapter(adapter);
recyclerView.SetItemViewCacheSize(4);
//recyclerView.ChildViewAttachedToWindow += new EventHandler<RecyclerView.ChildViewAttachedToWindowEventArgs>(OnChildViewAttached);
//recyclerView.ChildViewDetachedFromWindow += new EventHandler<RecyclerView.ChildViewDetachedFromWindowEventArgs>(OnChildViewDetached);
refresher = view.FindViewById<SwipeRefreshLayout>(Resource.Id.refresher);
refresher.SetColorSchemeColors(Resource.Color.accent);
progress = view.FindViewById<ProgressBar>(Resource.Id.progressbar_loading);
progress.Visibility = ViewStates.Gone;
return view;
}
}
I didn't read your entire code but I looked at the site you linked in your question. The functionality of the hidden action bar you want to use is handled by CollapsingToolbarLayout in the support library. To know how to use it, go to Cheesesquare. It is a complete example of the support library widgets and can be built and run without any changes.
Edit:
RecyclerView has a method named AddOnScrollListener. Use it instead of the OnScrollChanged. If you use an inherited class from RecyclerView, you can call it in all of the constructors of that class.

OnButtonPressed issue

Started with Xamarin Android yesterday and can't seem to figure out why the Back Button script(s) won't be called.
Searched and seen that a lot of people recommend something like this:
public override void OnBackPressed()
{
Toast.MakeText(this, "Back Button Pressed", ToastLength.Short).Show();
}
However this doesn't stop my phone or the android emulator from closing the app instantly.
Most of the things I have found about this thread I haven't managed to make work for some reason or they won't be called.
Thanks
Update:
Checked another project. It works 100% there with the same code as above. Not sure what makes it not work in my project
Update
Here is some of the code. I know it's terrible but I'm just messing around trying to learn as I'm a total newbie with Xamarin & Android - Feel free to give links on something I should read however!
namespace Workout_App {
[Activity(Label = "Workout App", MainLauncher = true)]
public class MainActivity : Activity
{
private List<Exercise> mItems, mItemsDay1;
private ListView mListView;
MyListViewAdapter adapter, adapter2;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
mListView = FindViewById<ListView>(Resource.Id.myListView); // myListView er navnet på objekte i AXML fila f.eks
mItems = new List<Exercise>();
mItemsDay1 = new List<Exercise>();
mItems.Add(new Exercise() { Name = "Day 1"});
mItems.Add(new Exercise() { Name = "Day 2"});
mItems.Add(new Exercise() { Name = "Day 3"});
mItemsDay1.Add(new Exercise() { Name = "Benkpress", Reps = "8x4", kg = 140});
mItemsDay1.Add(new Exercise() { Name = "Lårpress", Reps = "8x4", kg = 58});
mItemsDay1.Add(new Exercise() { Name = "BankPro", Reps = "8x4", kg = 22});
adapter = new MyListViewAdapter(this, mItems);
adapter2 = new MyListViewAdapter(this, mItemsDay1);
mListView.Adapter = adapter;
mListView.ItemClick += mListView_ItemClick; // subscribes it, - to unsub
mListView.ItemLongClick += mListView_ItemLongClick;
// mListView.ItemClick += mListView_ItemClick2;
}
public override void OnBackPressed()
{
Toast.MakeText(this, "Back Button Pressed Detected", ToastLength.Short).Show();
}
void mListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
mListView.Adapter = adapter2;
}
And this is the view
namespace Workout_App {
class MyListViewAdapter : BaseAdapter<Exercise>
{
public List<Exercise> mItems;
private Context mContext;
public MyListViewAdapter(Context context, List<Exercise> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get { return mItems.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override Exercise this[int position]
{
get { return mItems[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if(row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.listview_row, null, false );
}
TextView txtName = row.FindViewById<TextView>(Resource.Id.txtName);
txtName.Text = mItems[position].Name;
TextView txtReps = row.FindViewById <TextView>(Resource.Id.txtReps);
txtReps.Text = mItems[position].Reps;
TextView txtKg = row.FindViewById<TextView>(Resource.Id.txtKg);
if(mItems[position].kg > 0) {
txtKg.Text = mItems[position].kg + " kg";
} else
{
txtKg.Text = "";
}
return row;
}
}
}

Swipe Refresh not working in xamarin.android webview

I am trying to implement SwipeRefreshLayout in a webview in Xamarin.android but the layout keeps loading infinitely only works well as a progress bar but when swiping to refresh it doesn't work. Please help me fix it.
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.gameofthrones);
myWebClient = new WebClient();
myWebView = FindViewById<WebView>(Resource.Id.webView);
myProgressBar = FindViewById<ProgressBar>(Resource.Id.progressBar);
myswipeRefreshLayout = FindViewById<SwipeRefreshLayout>(Resource.Id.refresher);
myswipeRefreshLayout.SetColorScheme(Resource.Color.Red, Resource.Color.Orange,
Resource.Color.Yellow, Resource.Color.Green,
Resource.Color.Blue, Resource.Color.Indigo,
Resource.Color.Violet);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
myWebView.Settings.JavaScriptEnabled = true;
myWebView.LoadUrl("http://www.google.com");
myWebView.SetWebViewClient(myWebClient);
//Toolbar will now take on default actionbar characteristics
SetSupportActionBar(toolbar);
SupportActionBar.Title = "GAME OF THRONES";
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeButtonEnabled(true);
myswipeRefreshLayout.Refresh += MyswipeRefreshLayout_Refresh;
}
private void MyswipeRefreshLayout_Refresh(object sender, EventArgs e)
{
myWebClient.myOnProgressChanged += (int state) =>
{
if (state == 0)
{
(sender as SwipeRefreshLayout).Refreshing = false;
myswipeRefreshLayout.Refreshing = false;
//page loaded no progress bar visible
//myProgressBar.Visibility = ViewStates.Invisible;
}
else
{
(sender as SwipeRefreshLayout).Refreshing = true;
myswipeRefreshLayout.Refreshing = true;
//myProgressBar.Visibility = ViewStates.Visible;
}
};
}
public override bool OnKeyDown(Android.Views.Keycode keyCode, Android.Views.KeyEvent e)
{
if (keyCode == Keycode.Back && myWebView.CanGoBack())
{
myWebView.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (item.ItemId == Android.Resource.Id.Home)
Finish();
return base.OnOptionsItemSelected(item);
}
}
public class WebClient : WebViewClient
{
public delegate void ToggleProgreeBar(int state);
public ToggleProgreeBar myOnProgressChanged;
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
view.LoadUrl(url);
return true;
}
public override void OnPageStarted(WebView view, string url, Bitmap favicon)
{
if (myOnProgressChanged != null)
{
myOnProgressChanged.Invoke(1);
}
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(WebView view, string url)
{
if (myOnProgressChanged != null)
{
myOnProgressChanged.Invoke(0);
}
base.OnPageFinished(view, url);
}
SwipeRefreshLayout.Refresh get triggered when user down swipes. According to your requirement, when user swipes, you need to manually refresh the webview:
private void SwipeRefresh_Refresh(object sender, System.EventArgs e)
{
webview.LoadUrl(webview.Url);
}
And register myWebClient.myOnProgressChanged event inside OnCreate. So codes should looks like below:
public class MainActivity : Activity
{
WebView webview;
SwipeRefreshLayout mySwipeRefresh;
WebClient myWebClient;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
webview = FindViewById<WebView>(Resource.Id.webview);
webview.Settings.JavaScriptEnabled = true;
webview.LoadUrl("http://www.google.com");
mySwipeRefresh = FindViewById<SwipeRefreshLayout>(Resource.Id.swiperefresh);
myWebClient = new WebClient();
//register myOnProgressChanged here
myWebClient.myOnProgressChanged += (int state) =>
{
if (state == 0)
{
mySwipeRefresh.Refreshing = false;
}
else
{
mySwipeRefresh.Refreshing = true;
}
};
webview.SetWebViewClient(myWebClient);
mySwipeRefresh.Refresh += SwipeRefresh_Refresh;
}
private void SwipeRefresh_Refresh(object sender, System.EventArgs e)
{
//refresh the webview when user swipes.
webview.LoadUrl(webview.Url);
}
}

PullToResharp Custom ListView Xamarin Android

Hi I want to add pull to refresh on my apps using this component PullToResharp, The project is great but im having problem adding custom listview in fragment, does anyone here done this before help me resolve it, thanks.
here is the code
fragment
namespace ListViewPullToRefresh.Fragments
{
public class SampleListFragment : SupportListFragment
{
private IPullToRefresharpView _ptrView;
private List<TableItem> _itemHeading = new List<TableItem>();
public SampleListFragment() : base()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.nav, null, false);
}
public override void OnViewStateRestored(Bundle savedInstanceState)
{
base.OnViewStateRestored(savedInstanceState);
_itemHeading.Add(new TableItem(){Heading = "Ivan", Subheading = "Guinto"});
_itemHeading.Add(new TableItem(){Heading = "Jonathan", Subheading = "Guinto"});
_itemHeading.Add(new TableItem(){Heading = "Keneth", Subheading = "Guinto"});
if (_ptrView == null && ListView is IPullToRefresharpView)
{
_ptrView = (IPullToRefresharpView)ListView;
_ptrView.RefreshActivated += ptr_view_RefreshActivated;
}
ListView.Adapter = new HomeScreenAdapter(this, _itemHeading);
}
private void ptr_view_RefreshActivated(object sender, EventArgs e)
{
View.PostDelayed(() =>
{
if (_ptrView != null)
{
_ptrView.OnRefreshCompleted();
}
}, 2000);
}
public override void OnDestroyView()
{
if (_ptrView != null)
{
_ptrView.RefreshActivated -= ptr_view_RefreshActivated;
_ptrView = null;
}
base.OnDestroyView();
}
public override void OnResume()
{
base.OnResume();
ListView.ItemClick += ListView_ItemClick;
}
public override void OnPause()
{
base.OnPause();
ListView.ItemClick -= ListView_ItemClick;
}
void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
Toast.MakeText(Activity,e.Position+ " Clicked",ToastLength.Short).Show();
}
}
HomeScreenAdapter.cs
public class HomeScreenAdapter :BaseAdapter<TableItem>
{
public HomeScreenAdapter(Activity content, List<TableItem> items)
{
_content = content;
_items = items;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = _items[position];
var view = convertView;
if (view == null)
view = _content.LayoutInflater.Inflate(Resource.Layout.CustomView, null);
view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Heading;
view.FindViewById<TextView>(Resource.Id.Text2).Text = item.Subheading;
return view;
}
public override int Count
{
get { return _items.Count; }
}
public override TableItem this[int position]
{
get { return _items[position]; }
}
}
}
im getting this error
Error 1 The best overloaded method match for 'ListViewPullToRefresh.HomeScreenAdapter.HomeScreenAdapter(Android.App.Activity, System.Collections.Generic.List)' has some invalid arguments C:\Users******\Documents\Visual Studio 2013\Projects\ListViewPullToRefresh\ListViewPullToRefresh\Fragments\SampleListFragment.cs 43 32 ListViewPullToRefresh
Error 2 Argument 1: cannot convert from 'ListViewPullToRefresh.Fragments.SampleListFragment' to 'Android.App.Activity' C:\Users****\Documents\Visual Studio 2013\Projects\ListViewPullToRefresh\ListViewPullToRefresh\Fragments\SampleListFragment.cs 43 54 ListViewPullToRefresh
when i putting my custom adapter to the fragment, i get the error here ListView.Adapter = new HomeScreenAdapter(this, _itemHeading); and here public HomeScreenAdapter(Activity content, List<TableItem> items)
{
_content = content;
_items = items;
}

Categories