Xamarin Android Listview ClickEvent doesn't work - c#

I am pretty new here, but I have problem and hope that you can help me to solve it. I've created a ListView in Xamarin Android, VS 2017. After configuring it I tried to add a click Event in the MainActivity. Unfortunately, after many tries, I recognized that this is not working. So it doesn't recognize if the ListView is clicked. I know that this is a very basic question, so may there is a simple answer or some basic mistakes I#ve made? Thank you very much!
public class MainActivity : Activity
{
private ListView Lenseslv;
private TextView textView1;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Lenseslv = FindViewById<ListView>(Resource.Id.Lenseslv);
textView1 = FindViewById<TextView>(Resource.Id.textView1);
Lenseslv.Adapter = new MyCustomListAdapter(UserData.Users);
}
public void Lenseslv_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
textView1.Text = ("ClickEvent");
}

you have to assign the event handler to your ListView
Lenseslv.ItemClick += Lenseslv_ItemClick

Related

event when the left menu is opened in xamarin forms shell

I am working with xamarin forms shell. I have 1 image and 1 label to assign the name and profile picture of the user.
I want every time the menu opens (press the button or drag to the right) to update that value again, but I can't find any events related to it. Someone please help me badly
Since there is no and won't be events such OnFlyoutOpened OnFlyoutClosed, you can listen to your Shell PropertyChanged event, if the property is FlyoutIsPresented then execute your code:
public AppShell()
{
InitializeComponent();
PropertyChanged += Shell_PropertyChanged;
}
private void Shell_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName.Equals("FlyoutIsPresented"))
if (FlyoutIsPresented)
OnFlyoutOpened(); //you will execute your code here
else
OnFlyoutClosed();
}
Depending on your requirement you will define OnFlyoutOpened() and OnFlyoutClosed() methods.
Thanks to #PureWeen guidance in discussion.
You could use custom renderer to get the event when you press the shell hamburger icon.
[assembly: ExportRenderer(typeof(AppShell), typeof(ShellCustomRenderer))]
namespace ShellDemo.Droid
{
public class ShellCustomRenderer : ShellRenderer
{
public ShellCustomRenderer(Context context) : base(context)
{
}
protected override IShellToolbarAppearanceTracker CreateToolbarAppearanceTracker()
{
return new ToolbarAppearance();
}
}
public class ToolbarAppearance : IShellToolbarAppearanceTracker
{
public void Dispose()
{
}
public void ResetAppearance(Android.Support.V7.Widget.Toolbar toolbar, IShellToolbarTracker toolbarTracker)
{
toolbar.NavigationClick += Toolbar_NavigationClick1;
}
private void Toolbar_NavigationClick1(object sender, Android.Support.V7.Widget.Toolbar.NavigationClickEventArgs e)
{
//this event would be fired when the hamburger icon clicked.
}
private void Toolbar_NavigationClick(object sender, Android.Support.V7.Widget.Toolbar.NavigationClickEventArgs e)
{
}
public void SetAppearance(Android.Support.V7.Widget.Toolbar toolbar, IShellToolbarTracker toolbarTracker, ShellAppearance appearance)
{
}
}
}

Xamarin.Android how to auto update RecyclerView

Following this article I created a simple application that displays a list. The list I get from a web service (.asmx web service).
I want to auto update RecyclerView every 5 seconds and I have no idea how to do it.
In WinForms I would have used the Timer component, but I don't know how this works in Xamarin.
MainActivity.cs
[Activity(Label = "CibMonitor", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : AppCompatActivity
{
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ConnectionItemsAdapter adapter;
ConnectionItem[] connectionItems;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var ci = new ConnectionItem();
//Get list from web service
connectionItems = ci.GetList().ToArray();
//Setup RecyclerView
adapter = new ConnectionItemsAdapter(this, connectionItems);
recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
recyclerView.SetAdapter(adapter);
ChangedData();
}
}
Update
I created new method in activity class as York Shen suggested
void ChangedData()
{
Task.Delay(5000).ContinueWith(t =>
{
var newData = ConnectionItem.GetList();
adapter.RefreshItems(newData);
ChangedData();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
This is my update method in adapter class:
public void RefreshItems(List<ConnectionItem> newItems)
{
items.Clear();
items = newItems;
NotifyDataSetChanged();
}
my app stops working, no exception only this message:
You can create a Task which can help you update recyclerView every 5 seconds:
void ChangedData()
{
Task.Delay(5000).ContinueWith(t =>
{
adapter.NotifyDataSetChanged();
ChangedData();//This is for repeate every 5s.
}, TaskScheduler.FromCurrentSynchronizationContext());
}
EDIT:
Sorry for late reply, calling the ChangedData() in Task.Delay() can resolve the repeate problem. You can invoke the ChangedData() in OnCreate() method. Hope this can help you. : )

Update Recycler view by button in toolbar

I writing app for Android using Xamarin.
I have this code in Activity for OnCreate method.
protected override int LayoutResource
{
get { return Resource.Layout.Main; }
}
private RecyclerView recyclerView;
private ProgressBar activityIndicator;
private RecyclerView.LayoutManager layoutManager;
protected override async void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
activityIndicator = FindViewById<ProgressBar>(Resource.Id.activityIndicator);
activityIndicator.Visibility = Android.Views.ViewStates.Visible;
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
recyclerView.SetLayoutManager(layoutManager);
var repository = new TestAppRepository();
var films = await repository.GetAllFilms();
var formsAdapter = new FormAdapter(films.results);
recyclerView.SetAdapter(formsAdapter);
activityIndicator.Visibility = Android.Views.ViewStates.Gone;
SupportActionBar.SetDisplayHomeAsUpEnabled(false);
SupportActionBar.SetHomeButtonEnabled(false);
I have Button in toolbar and need to refresh Recycler when I tap this button.
Here is calling of it for display
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.home, menu);
return base.OnCreateOptionsMenu(menu);
}
How I need to write code to refresh Recycler?
Thank's for help
Use the button's setOnClickListener method and implement the onClick method of the new OnClickListener In the onClick method called the RecyclerView adapter's notifydatasetchanged()

Custom dialog collapsing when title is removed

My app is supposed to have a button in the main activity that when pressed should show a custom dialog box that will be used as a register form for users. The problem is when I remove the title bar of my custom dialog window collapses horizontally. Any advise on how to fix this? Is the idea of using a fragment as a registration form a good one? TIA
Here is the image to Illustrate
Here is what it looks like with the title bar
Here is the code for the Main Activity
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mbtnfragment = FindViewById<Button>(Resource.Id.MyButton);
mbtnfragment.Click += mbtnfragment_Click;
}
void mbtnfragment_Click(object sender, EventArgs e)
{
FragmentTransaction transaction = FragmentManager.BeginTransaction();
create_dialog dialog = new create_dialog();
dialog.Show(transaction, "Fragment Dialog");
Console.WriteLine("Fragment created");
}
Code for the create_dialog class
class create_dialog: DialogFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState)
{
base.OnCreateView(inflater, container, savedInstancesState);
var view = inflater.Inflate(Resource.Layout.fragment_dialog, container, false);
return view;
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
Dialog.Window.RequestFeature(WindowFeatures.NoTitle);
base.OnActivityCreated(savedInstanceState);
}
}
}
change the fragment_dialog layout's width from wrap_content to match_parent or a defined size
You can set a style without title to your custom dialog
#Override
public void onCreateDialog(Bundle savedInstanceState) {
setStyle(STYLE_NO_TITLE, 0);
}
Or you can set a theme in the second parameter like Theme.AppCompat.Dialog...

Xamarin android OnSharedPreferenceChangeListener

I've got this activity and have a problem with OnSharedPreferenceChanged not being called.
My use case is that i want to show preference value in preference description. Code below translated is translated from java where works perfectly fine.
[Activity]
public class PrefActivity : PreferenceActivity, ISharedPreferencesOnSharedPreferenceChangeListener
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
AddPreferencesFromResource(Resource.Xml.preferences);
}
protected override void OnResume()
{
base.OnResume();
PreferenceScreen.SharedPreferences.
RegisterOnSharedPreferenceChangeListener(this);
}
protected override void OnPause()
{
base.OnPause();
PreferenceScreen.SharedPreferences.
UnregisterOnSharedPreferenceChangeListener(this);
}
#region ISharedPreferencesOnSharedPreferenceChangeListener implementation
public void OnSharedPreferenceChanged(ISharedPreferences sharedPreferences, string key)
{
Preference pref = FindPreference(key);
if (pref is ListPreference)
{
ListPreference listPref = (ListPreference)pref;
listPref.Summary = listPref.Entry;
}
}
#endregion
}
Iam using Xamarin.Android v4.6.8 code above is my last attempt to make this working ive also tried using PreferenceScreen.PreferenceChange event for handling preference changes but with no results.
Tahnks for help.
Ive found solution! changing
PreferenceScreen.SharedPreferences.
RegisterOnSharedPreferenceChangeListener(this);
to
PreferenceManager.GetDefaultSharedPreferences(this).
RegisterOnSharedPreferenceChangeListener(this);
will do the trick.
I hope that it will help somebody.

Categories