RecyclerView not showing - Xamarin .Droid - c#

To me, it seems there's nothing wrong in my code but my recyclerView is not showing up. Please look into my code if the adapter is well set up. Thank you. Please what am i missing in my adapter? The page appears empty although i see that the datasnapShot in my adapter runs but my recyclerView doesn't show.
Adapter
public class PhotoHolder : RecyclerView.ViewHolder
{
public ImageView ImgPhotos;
public PhotoHolder(View itemView):base(itemView)
{
ImgPhotos = (ImageView)itemView.FindViewById(Resource.Id.imageView);
}
public class PhotoAdapter : RecyclerView.Adapter, IValueEventListener
{
public PhotoAdapter(List<Photos> Photos, Context mContext)
{
this.Photos = Photos;
this.mContext = mContext;
photos = (PhotosActivity)mContext;
mDatabaseImage = FirebaseDatabase.Instance.Reference.Child("Photos");
mDatabaseImage.AddValueEventListener(this);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
hold = holder as PhotoHolder;
hold.ImgPhotos.SetImageResource(Resource.Drawable.cheese_5);
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.list_photos, parent, false);
PhotoHolder holder = new PhotoHolder(v);
return holder;
}
public override int ItemCount
{
get { return Photos.Count; }
}
public void OnCancelled(DatabaseError error)
{
throw new NotImplementedException();
}
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Children?.ToEnumerable<DataSnapshot>();
foreach (DataSnapshot item in items)
{
map = (HashMap)item.Value;
imageUrl = new FilePhotos(map.Get("URL").ToString());
}
}
}
}
PhotoActivity
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
FrameLayout content = (FrameLayout)FindViewById(Resource.Id.content_frame);
LayoutInflater.Inflate(Resource.Layout.PhotoView, content);
adapter = new PhotoAdapter(Photos, this);
rv = FindViewById<RecyclerView>(Resource.Id.recyclerView);
rv.SetLayoutManager(new LinearLayoutManager(this));
rv.SetItemAnimator(new DefaultItemAnimator());
rv.SetAdapter(adapter);
adapter.NotifyDataSetChanged();
}

Related

How to Use ArrayAdapter with Multiple Textview columns in listView Xamarin Android

I have listview with 4 columns like ItemLookupCode,Quantity,Description,Price
I am adding full code i am sorting list on button click.
i have issue in following Populate() to call 4 textview
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.PriceCheckList);
List<string> list = new List<string>();
foreach (crItem item in listObject)
{
list.Add(item.ItemLookupCode);
list.Add(Convert.ToString(item.Quantity));
list.Add(item.Description);
list.Add(Convert.ToString(item.Price));
}
spacecrafts = list.ToArray();
this.InitializeViews();
this.SortData(ascending);
this.ascending = !ascending;
}
SortBtnItemLookupCode.Click += sortBtn_Click;
void sortBtn_Click(object sender, EventArgs e)
{
SortData(ascending);
this.ascending = !ascending;
}
private void InitializeViews()
{
listView = FindViewById<ListView>(Resource.Id.listView);
SortBtnItemLookupCode = FindViewById<Button>(Resource.Id.SortBtnItemLookupCode);
}
private void Populate()
{
ArrayAdapter adapter = new ArrayAdapter<string>(this, Resource.Layout.PriceCheckListTemplate, Resource.Id.lblItemLookupCode, spacecrafts);
listView.SetAdapter(adapter);
}
private void SortData(bool asc)
{
if (asc)
{
Array.Sort(spacecrafts);
}
else
{
Array.Reverse(spacecrafts);
}
Populate();
}
}
I want to assign all above 4 object to Textview but currently ArrayAdapter accept only one Textview like i have use below Resource.Id.lblItemLookupCode but How i can assign 4 object to 4 columns Textview in ArrayAdapter
Help much appreciated
Thanks in advance
Try create model class to define data for the listView's item, then customize a custom Adapter to populate the data.
Check the code:
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
string[] items = new string[] { "Vegetables", "Fruits", "Flower Buds", "Legumes", "Bulbs", "Tubers" };
List<CustomModel> list = new List<CustomModel>();
//add data
CustomAdapter adapter = new CustomAdapter(list);
ListView listview_ = FindViewById<ListView>(Resource.Id.listview_);
listview_.SetAdapter(adapter);
}
}
public class CustomModel
{
public string Value1 { get; set; }
...
}
public class CustomAdapter : BaseAdapter<CustomModel>
{
List<CustomModel> list = new List<CustomModel>();
public _Adapter(List<CustomModel> list)
{
this.list = list;
}
public override CustomModel this[int position]
{
get
{
return list[position];
}
}
public override int Count
{
get
{
return list.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var view = convertView;
view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.layout1, parent, false);
//specify value to the each textView
var textview = view.FindViewById<TextView>(Resource.Id.text_1);
textview.Text = list[position].Value1;
...
return view;
}
}

Updating RecyclerView in a Fragment - Xamarin Android

I have a 3 fragments on my view pager. On my 3rd fragment is a recyclerViewer which contains contact list. Now, i am finding it difficult as to how to update my contact list (recycleViewer with data) from my database. recycleview in Fragment.axml is inflated from Fragment 3.cs.
Fragment 3.cs
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
RecyclerView recyclerView = inflater.Inflate(Resource.Layout.Fragment3, container, false) as RecyclerView;
implementRecyclerView(recyclerView);
return recyclerView;
}
private void SetUpRecyclerView(RecyclerView recyclerView)
{
recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));
recyclerView.SetAdapter(Adapter);
recyclerView.Click += eventClicked;
Adapter.NotifyDataSetChanged();
recyclerView.SetItemClickListener((rv, position, view) =>
{
//An item has been clicked
Context context = view.Context;
Intent intent = new Intent(context, typeof(EventDetailActivity));
context.StartActivity(intent);
});
}
This is where my RecycleView that actually displays the contact list after being inflated in the Fragment 3.cs
Fragment 3 axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
//id of RecycleView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In this activity, I add some data to my database. After adding, i call the RefreshListWithNewData() to update my RecyclerView (contact list). I keep getting NullReference trying to get the id of the RecycleView.
SomeActivity.cs
JavaList<Contact> myContactList = new JavaList<Contact>();
private async void AddNewGames(){
//add contacts to database
await RefreshListWithNewData()
}
private async Task RefreshListWithNewData(){
foreach(var item in items){
Contact people = new Contact();
people.Name = item.Object.Name;
myContactList.Add(people);
}
//trying to update recycleview in Fragment 3.cs
refreshRecycler = (RecyclerView)FindViewById(Resource.Id.recycleview)
adapter = new ContactAdapter(myContactList);
refreshRecycler.SetAdapter(adapter);
My question is why can't i reach that RecycleView even after i have given it an id called recycleview?
Updated Fragment3.cs
public class Fragment3 : SupportFragment
{
public RecyclerView refresh;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
RecyclerView recyclerView = inflater.Inflate(Resource.Layout.Fragment3, container, false) as RecyclerView;
SetUpRecyclerView(recyclerView);
return recyclerView;
}
private void SetUpRecyclerView(RecyclerView recyclerView)
{
//var value= GetRandomSubList(PeaceEventsCollection.GetPeaceEvents(), 5);
var value = PeaceEventsCollection.GetPeaceEvents();
recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));
var Adapter = new EventAdapter(PeaceEventsCollection.GetPeaceEvents());
recyclerView.SetAdapter(Adapter);
recyclerView.Click += eventClicked;
Adapter.NotifyDataSetChanged();
recyclerView.SetItemClickListener((rv, position, view) =>
{
//An item has been clicked
Context context = view.Context;
Intent intent = new Intent(context, typeof(EventDetailActivity));
intent.PutExtra(EventDetailActivity.EXTRA_NAME, value[position].EName);
intent.PutExtra(EventDetailActivity.EXTRA_DETAIL, value[position].EDescritption);
intent.PutExtra(EventDetailActivity.EXTRA_DATE, value[position].EDate);
//perform activity to event page
context.StartActivity(intent);
});
}
private JavaList<PeaceEvents> GetRandomSubList(JavaList<PeaceEvents> items, int amount)
{
JavaList<PeaceEvents> list = new JavaList<PeaceEvents>();
Random random = new Random();
while (list.Count < amount)
{
list.Add(items[random.Next(items.Count)]);
}
return list;
}
private void eventClicked(object sender, EventArgs e)
{
Intent showEvent = new Intent(Context, typeof(EventActivity));
this.StartActivity(showEvent);
}
public class EventAdapter : RecyclerView.Adapter
{
private JavaList<PeaceEvents> peaceEvents;
public EventAdapter(JavaList<PeaceEvents> peaceEvents)
{
this.peaceEvents = peaceEvents;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
EventHolder hold = holder as EventHolder;
hold.EventName.Text = peaceEvents[position].EName;
hold.EventImg.SetImageResource(peaceEvents[position].EImage);
hold.EventDate.Text = peaceEvents[position].EDate;
hold.EventVenue.Text = peaceEvents[position].EVenue;
hold.EventDescription.Text = peaceEvents[position].EDescritption;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.List_Event, parent, false);
EventHolder holder = new EventHolder(v);
return holder;
}
public override int ItemCount
{
get { return peaceEvents.Size(); }
}
}
}
public class EventHolder : RecyclerView.ViewHolder
{
public TextView EventName;
public ImageView EventImg;
public TextView EventDate;
public TextView EventVenue;
public TextView EventDescription;
public TextView textIcon;
public TextView EventDetailDescription;
public EventHolder(View itemView) : base(itemView)
{
EventName = itemView.FindViewById<TextView>(Resource.Id.textViewEvent);
EventImg = itemView.FindViewById<ImageView>(Resource.Id.imageView);
EventDate = itemView.FindViewById<TextView>(Resource.Id.textViewDate);
EventVenue = itemView.FindViewById<TextView>(Resource.Id.textViewVenue);
EventDescription = itemView.FindViewById<TextView>(Resource.Id.textViewDescription);
}
}
EventActivity
public class EventActivity : AppCompatActivity
{
private EditText EventName;
private EditText EventDateTime;
private EditText EventVenue;
private EditText EventDescription;
private ProgressBar circular_progress;
private Button saveData;
private LinearLayout list_view;
private RecyclerView recycle;
// private EventAdapter adapter;
JavaList<PeaceEvents> peace_Events = new JavaList<PeaceEvents>();
// private PeaceEvents selectedEvents;
private const string FirebaseUrl = "";
private DrawerLayout mDrawerLayout;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Events);
// Create your application here
SupportToolbar toolBar = FindViewById<SupportToolbar>(Resource.Id.toolBar);
SetSupportActionBar(toolBar);
//view
circular_progress = FindViewById<ProgressBar>(Resource.Id.circularProgress);
EventName = FindViewById<EditText>(Resource.Id.eventName);
EventDateTime = FindViewById<EditText>(Resource.Id.txtDateAndTime);
EventVenue = FindViewById<EditText>(Resource.Id.venue);
EventDescription = FindViewById<EditText>(Resource.Id.txtDescribe);
list_view = FindViewById<LinearLayout>(Resource.Id.list_view);
saveData = FindViewById<Button>(Resource.Id.btnLogin);
saveData.Click += saveEventData;
SupportActionBar ab = SupportActionBar;
ab.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
ab.SetDisplayHomeAsUpEnabled(true);
mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
if (navigationView != null)
{
SetUpDrawerContent(navigationView);
}
}
private void saveEventData(object sender, EventArgs e)
{
CreateEvent();
}
private async void CreateEvent()
{
PeaceEvents events = new PeaceEvents();
events.EName = EventName.Text;
events.EDate = EventDateTime.Text;
events.EVenue = EventVenue.Text;
events.EDescritption = EventDescription.Text;
var firebase = new FirebaseClient(FirebaseUrl);
//add item
var item = await firebase.Child("").PostAsync<PeaceEvents>(events);
await LoadData();
}
private async Task LoadData()
{
circular_progress.Visibility = ViewStates.Visible;
var firebase = new FirebaseClient(FirebaseUrl);
var items = await firebase.Child("").OnceAsync<PeaceEvents>();
peace_Events.Clear();
EventAdapter adpater;
foreach(var item in items){
PeaceEvents events = new PeaceEvents();
events.EName = item.Object.EName;
events.EDate = item.Object.EDate;
events.EDescritption = item.Object.EDescritption;
events.EVenue = item.Object.EVenue;
events.EImage = item.Object.EImage;
peace_Events.Add(events);
}
// Fragment3.UpdateContactList<Ja>(peace_Events);
//adpater = new EventAdapter(peace_Events);
////recycle.SetAdapter(adpater);
////recycle.SetLayoutManager(new LinearLayoutManager(this));
//adpater.NotifyDataSetChanged();
//recycle.SetAdapter(adpater);
circular_progress.Visibility = ViewStates.Invisible;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Android.Resource.Id.Home:
mDrawerLayout.OpenDrawer((int)GravityFlags.Left);
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
private void SetUpDrawerContent(NavigationView navigationView)
{
navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
{
int id = e.MenuItem.ItemId;
switch (id)
{
case Resource.Id.nav_home:
Intent home = new Intent(this, typeof(MainActivity));
this.StartActivity(home);
GC.Collect();
break;
case Resource.Id.nav_peacehero:
Intent intent = new Intent(this, typeof(PeaceFragement));
this.StartActivity(intent);
GC.Collect();
break;
//case Resource.Id.nav_discussion:
// Intent discuss = new Intent(this, typeof(PeaceHeroActivity));
// this.StartActivity(discuss);
// break;
//case Resource.Id.nav_event:
// Intent peace_event = new Intent(this, typeof(PeaceHeroActivity));
// this.StartActivity(peace_event);
// break;
//case Resource.Id.nav_donate:
//Intent donate = new Intent(this, typeof(PeaceHeroActivity));
//this.StartActivity(donate);
//break;
}
e.MenuItem.SetChecked(true);
mDrawerLayout.CloseDrawers();
};
}
}
}

Xamarin Image Grid from Folder

I am trying to display an Image Grid with Text. Using Images from a Folder. I have tries various approaches and tutorials with no success. I have both READ and WRITE permissions for the Internal and External Storage. Whenever I debug the application all I get is a blank screen. I have tried setting a breakpoint on the Adapters GetView() method which never gets hit.
Here is my MainActivity OnCreate() method:
protected override void OnCreate(Bundle bundle)
{
if (!_dir.Exists()) { _dir.Mkdir(); }
base.OnCreate(bundle);
SetContentView(R.Layout.Main);
string[] FilePath = null;
string[] FileName = null;
if (_dir.IsDirectory)
{
DroidIO.File[] imageList = _dir.ListFiles();
FilePath = new string[imageList.Length];
FileName = new string[imageList.Length];
for (int i = 0; i < imageList.Length; i++)
{
FilePath[i] = imageList[i].AbsolutePath;
FileName[i] = imageList[i].Name;
}
}
var gvImageList = FindViewById<GridView>(R.Id.gvImageList);
gvImageList.SetAdapter(new ImagesFromFolderAdapter(this, FilePath, FileName));
gvImageList.ItemClick += delegate { gvImageList_ItemClick(); };
}
And my Image Adapter Class:
public class ImagesFromFolderAdapter : BaseAdapter
{
private Activity context;
private string[] filePath;
private string[] fileName;
public ImagesFromFolderAdapter(Activity c, string[] fp, string[] fn)
{
this.context = c;
this.fileName = fn;
this.filePath = fp;
}
public override int Count { get; }
public int GetCount()
{
return filePath.Length;
}
public override Java.Lang.Object GetItem(int position)
{
return position;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = context.LayoutInflater.Inflate(R.Layout.gallery_item_layout, null);
view.FindViewById<ImageView>(R.Id.gitemImage).SetImageBitmap(BitmapFactory.DecodeFile(filePath[position]));
view.FindViewById<TextView>(R.Id.gitemText).Text = fileName[position];
return view;
}
}
Any ideas where I am going wrong? I am currently using an LG G3 as a debug device if this helps. Thankyou for any help in advance.
You returned a zero count for your grid adapter.
Change
public override int Count { get; }
To
public override int Count
{
get { return filePath.Length; }
}

xamarin android ExpandableListView: remove or hide a childview from group

How to remove a child view from group after clicking a button of the child view?
class ExpandableListAdapter : BaseExpandableListAdapter {
private ListView listview;
private LinearLayout mainLayout;
private View linearLayout;
public Activity _context;
TextView txtListChild;
private List<string> _listDataHeader; // header titles
private Dictionary<string, List<string>> _listDataChild;
public ExpandableListAdapter(Activity activity, List<string> listDataHeader, Dictionary<String, List<string>> listChildData) {
//, Dictionary<String, List<string>> listChildData2
this._context = activity;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
// this._listDataChild2 = listChildData2;
}
public override Java.Lang.Object GetChild(int groupPosition, int childPosition) {
return _listDataChild[_listDataHeader[groupPosition]][childPosition];
}
public override long GetChildId(int groupPosition, int childPosition) {
return childPosition;
}
public override View GetChildView(int groupPosition, int childPosition, bool isLastChild, View convertView, ViewGroup parent) {
string childText = (string)GetChild(groupPosition, childPosition);
convertView = null;
if (convertView == null) {
convertView = _context.LayoutInflater.Inflate(Resource.Layout.childRowWithButton, null);
Button no = (Button)convertView.FindViewById(Resource.Id.gono);
no.Click += delegate{
// I want hide my child
};
txtListChild.Text = childText;
}
return convertView;
}
public override int GetChildrenCount(int groupPosition) {
return _listDataChild[_listDataHeader[groupPosition]].Count;
}
public override Java.Lang.Object GetGroup(int groupPosition) {
return _listDataHeader[groupPosition];
}
public override long GetGroupId(int groupPosition){
return groupPosition;
}
public override View GetGroupView(int groupPosition, bool isExpanded, View convertView, ViewGroup parent){
string headerTitle = (string)GetGroup(groupPosition);
convertView = convertView ? ? _context.LayoutInflater.Inflate(Resource.Layout.HeaderCustomLayout, null);
var lblListHeader = (TextView)convertView.FindViewById(Resource.Id.Header);
//string headerTitle2 = (string)GetGroup(groupPosition);
//var ListHeader2 = (TextView)convertView.FindViewById(Resource.Id.Header2);
//ListHeader2.Text = headerTitle2;
lblListHeader.Text = headerTitle;
return convertView;
}
public override int GroupCount{
get{
return _listDataHeader.Count;
}
}
public override bool HasStableIds{
get{
return false;
}
}
public override bool IsChildSelectable(int groupPosition, int childPosition){
return true;
}
}
You can use listView.SetOnChildClickListener() to remove your child view as following code:
public class MainActivity : Activity , IOnChildClickListener
{
ExpandableListView listView;
List<Data> newDataList;
ExpandableDataAdapter myadapter;
public bool OnChildClick(ExpandableListView parent, View clickedView, int groupPosition, int childPosition, long id)
{
newDataList.RemoveAt(0);
myadapter.NotifyDataSetChanged();
return true;
}
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
newDataList = Data.SampleData();
myadapter = new ExpandableDataAdapter(this, newDataList);
listView = FindViewById<ExpandableListView> (Resource.Id.myExpandableListview);
listView.SetAdapter (myadapter);
listView.SetOnChildClickListener(this);
}
}
In my sample, I just remove the first item of the child, You can use the int groupPosition, int childPosition to get the current location you click. And remove it from your listData. Remember to call adapter.NotifyDataSetChanged(); when you change the data set.
I am using the ExpandableListView sample from github
Screen shot:

Xamarin\Android Development - How do I change Fragments by clicking on a listview item?

Here is the bit of code I have so far :
namespace MyTestApp2
{
[Activity(Label = "Simple ListView", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : FragmentActivity {
private CustomViewPager _viewPager;
string[] items;
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
//items = new string[] { "Jon Douglas", "Jax The Cat", "Moxxi The Cat", "Andie The Dog" };
//ListAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, items);
_viewPager = FindViewById<CustomViewPager>(Resource.Id.ViewPager);
_viewPager.Adapter = new MyFragmentAdapter(SupportFragmentManager);
}
//protected override void OnListItemClick(ListView l, View v, int position, long id)
//{
// var t = items[position];
// Toast.MakeText(this, t, Android.Widget.ToastLength.Short).Show();
//}
}
public class MyFragmentAdapter : FragmentPagerAdapter
{
public MyFragmentAdapter(Android.Support.V4.App.FragmentManager fm) : base(fm)
{}
public override int Count
{
get {
return 5; }
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
//List<Android.Support.V4.App.Fragment> test = new List<Android.Support.V4.App.Fragment>();
//test.Add(new MyFragment());
//test.Add(new MyFragment2());
if (position == 0)
return new MyFragment();
else
return new MyFragment2();
//return test[position] == null ? new MyFragment() : test[position];
}
public override void SetPrimaryItem(View container, int position, Java.Lang.Object #object)
{
base.SetPrimaryItem(container, position, #object);
}
}
public class MyFragment : Android.Support.V4.App.Fragment
{
string[] animals = new string[5] { "Tiger", "Lion", "Zebra", "Cheetah", "Giraffe" };
Context thiscontext;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.MyLayout, container, false);
var test = view.FindViewById<ListView>(Resource.Id.listView1);
thiscontext = container.Context;
test.Adapter = new ArrayAdapter(Activity, Android.Resource.Layout.SimpleListItem1, animals);
test.ItemClick += OnListItemClick;
return view;
// return base.OnCreateView(inflater, container, savedInstanceState);
}
void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
//var listView = sender as ListView;
//var t = animals[e.Position];
////Android.Widget.Toast.MakeText(MyFragment.this, "kjh", Android.Widget.ToastLength.Short).Show();
//Android.Widget.Toast.MakeText(thiscontext, t, ToastLength.Short).Show();
//var adapter = new MyFragmentAdapter(this.FragmentManager);
//adapter.SetPrimaryItem(this.View, 1, this);
var test = new CustomViewPager(thiscontext, null);
test.SetCurrentItem(1, true);
}
}
public class MyFragment2 : Android.Support.V4.App.Fragment
{
private string[] animals = new string[5] { "Mackeral", "Sea Lion", "Dolphins", "Sardine", "Whales" };
Context thiscontext;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.MyLayout, container, false);
var test = view.FindViewById<ListView>(Resource.Id.listView1);
thiscontext = container.Context;
test.Adapter = new ArrayAdapter(Activity, Android.Resource.Layout.SimpleListItem1, animals);
test.ItemClick += OnListItemClick;
return view;
// return base.OnCreateView(inflater, container, savedInstanceState);
}
void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var listView = sender as ListView;
var t = animals[e.Position];
Android.Widget.Toast.MakeText(thiscontext, t, Android.Widget.ToastLength.Short).Show();
}
}
public class CustomViewPager : ViewPager
{
private bool enabled;
public CustomViewPager(Context context, Android.Util.IAttributeSet attr) : base(context, attr) { this.enabled = true; }
public override bool OnTouchEvent(MotionEvent e)
{
if(this.enabled)
return base.OnTouchEvent(e);
return false;
}
public override bool OnInterceptHoverEvent(MotionEvent e)
{
if(this.enabled)
return base.OnInterceptHoverEvent(e);
return false;
}
public override void SetCurrentItem(int item, bool smoothScroll)
{
base.SetCurrentItem(item, smoothScroll);
}
}
}
As you can see from the above, i have attempted to add code to the OnListItemClick event, however, ive not succeeded in changing the fragment.
So, I need the code to do the following :
Not to change pages when swiping left or right
but only change pages by clicking a list item
Am I going in the right direction ?
I was able to resolve my issue by doing the following :
Changing my Fragment class to a ListFragment class
Setting my ViewPager as a property
Using the ViewPager property to setCurrentItem to the next ListFragment class
Code :
public class MyFragment : Android.Support.V4.App.ListFragment
{
string[] animals = new string[5] { "Tiger", "Lion", "Zebra", "Cheetah", "Giraffe" };
CustomViewPager vpager;
Context thiscontext;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
thiscontext = container.Context;
var view = inflater.Inflate(Resource.Layout.Main, container, true);
var vp = view.FindViewById<CustomViewPager>(Resource.Id.ViewPager);
vpager = vp;
return base.OnCreateView(inflater, container, savedInstanceState);
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
this.ListAdapter = new ArrayAdapter<string>(Activity, Android.Resource.Layout.SimpleExpandableListItem1, animals);
}
public override void OnListItemClick(ListView l, View v, int position, long id)
{
// We can display everything in place with fragments.
// Have the list highlight this item and show the data.
ListView.SetItemChecked(position, true);
// vpager.SetOnPageChangeListener(new PagerListener());
vpager.SetCurrentItem(1, true);
}
}
This took a few hours to resolve and may help others.

Categories

Resources