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();
};
}
}
}
Related
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;
}
}
I have created a project in which I am retrieving data from the database and display it into a ListView. See image below.
Here is the code for retrieving data for the ListView
public class MainActivity : Activity
{
public static Context context;
public static List<UserInfo> UserInfoList = new List<UserInfo>();
public static ListView ListView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
ListView = FindViewById<ListView>(Resource.Id.Listview);
GetList list = new GetList();
list.Execute();
}
public class GetList : AsyncTask
{
Context con;
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] #params)
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient( );
var _WebApiUrl = string.Format("URL");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage messge = client.GetAsync(_WebApiUrl).Result;
var Return_EventList = messge.Content.ReadAsStringAsync().Result;
var EventList = JsonConvert.DeserializeObject<List<UserInfo>>(Return_EventList);
foreach (var data in EventList)
{
UserInfoList.Add(data);
}
return true;
}
protected override void OnPreExecute()
{
base.OnPreExecute();
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
ListView.Adapter = new UserInfoListAdapter(context, UserInfoList);
}
}
class UserInfoListAdapter : BaseAdapter<UserInfo>
{
private List<UserInfo> mItem = new List<UserInfo>();
private Context context;
public UserInfoListAdapter(Context mcontext, List<UserInfo> mItems)
{
mItem.Clear();
mItem = mItems;
context = mcontext;
this.NotifyDataSetChanged();
}
public override UserInfo this[int position]
{
get
{
return mItem[position];
}
}
public override int Count
{
get
{
return mItem.Count;
}
}
public Context MContext { get; private set; }
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View listitem = convertView;
listitem = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ListViewDesign, parent, false);
TextView TxtName = listitem.FindViewById<TextView>(Resource.Id.TxtName);
TextView TxtNumber = listitem.FindViewById<TextView>(Resource.Id.TxtNumber);
TxtName.Text = mItem[position].firstname;
TxtNumber.Text = mItem[position].contact_no;
listitem.Click += (object sender, EventArgs e) =>
{
Toast.MakeText(parent.Context, "Clicked " + mItem[position].firstname, ToastLength.Long).Show();
};
return listitem;
}
}
}
I want to put buttons in the ListView, one per row. Here is the example of how I want to implement it
Now when user click on button, a pdf file should download based on current id from database. For example in my database xray id is 1, so when user download pdf for xray it should download based on id which is 1
Place TableLayout in your 'ListViewDesign' android layout in order to
get required view (or it can be achieved by Linear Layout by setting
its orientation horizontal and its layout_weight)
Place Button in Fourth Column
Remove Click Event from GetView Method
Access Button in GetView Method
Button DownloadButton = view.FindViewbyId<Button>(Resource.Id.btn_download);
DownloadButton.Click += delegate { DownloadFile( link + mItem[position].Id ) };
Add Namespaces
using System.Net;
using System.IO;
using System.Text;
Add a new method in your listView Adapter Class
private void DownloadFile(string url)
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string localFilename = "downloaded.txt";
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllText(localPath, text); // writes to local storage
};
var url = new Uri("http://xamarin.com");
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
RunOnUiThread(() => {
Toast.MakeText(this, "Download Completed", ToastLength.Short).Show();
});
}
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();
}
I have a simple activity which textview and listview. My list view use custom adapter to display data also in the adapter i have itemClick method. I would like to change textview after clicking the list item. My problem is I don't know how to find the text view from list adapter? I'll try something like this:
TextView TeamSelect = (TextView)activity.FindViewById(Resource.Id.tvSelectPlayers);
TeamSelect.SetText("Players", TextView.BufferType.Normal);
but this give me an error:
System.NullReferenceException: Object reference not set to an instance of an object
Here is my adapter:
public HomePlayersAdapter(Activity context)
{
mInflater = LayoutInflater.From(context);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
public override int Count //return number of items in the list
{
get { return homePlayers.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return position;
}
public Player GetObject(int position)
{
return this.homePlayers.ElementAt(position);
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
var y = (itemPos.IndexOf(position) + 1);
var item = homePlayers[position];
if (convertView == null || holder == null)
{
convertView = mInflater.Inflate(Resource.Layout.RowPlayers, null);
holder = new ViewHolder();
holder.playerName = convertView.FindViewById<TextView>(Resource.Id.tvRow); //set holder label with label list id in the view
convertView.Tag = (holder);
}
else
{
holder = (ViewHolder)convertView.Tag;
}
holder.playerName.SetText(item.firstName + " " + item.lastName, TextView.BufferType.Normal);//set data label
holder.playerName.TextSize = 30;
if (clickCount >= 15)
{
subs = 1;
Android.Widget.Toast.MakeText(context, "ok", Android.Widget.ToastLength.Short).Show();
}
else
{
subs = 0;
}
y = (itemPos.IndexOf(position) + 1);
if (itemPos.Contains(position))
{
holder.playerName.SetTextColor(mInflater.Context.Resources.GetColor(Resource.Drawable.green));
holder.playerName.SetText(y + ". " + item.firstName + " " + item.lastName, TextView.BufferType.Normal);//set data label
}
else
{ holder.playerName.SetTextColor(mInflater.Context.Resources.GetColor(Resource.Drawable.white));
}
return convertView;
}
public void itemClick(int position)
{
if (!itemPos.Contains(position))
{
clickCount++;
var selectFixtureActivity = new Intent(context, typeof(SelectPlayers));
selectFixtureActivity.PutExtra("clickCount", clickCount);
holder.playerName.SetTextColor(mInflater.Context.Resources.GetColor(Resource.Drawable.green));
itemPos.Add(position);
NotifyDataSetChanged();
insertPlayer(position);
}
else
{
clickCount--;
var selectFixtureActivity = new Intent(context, typeof(SelectPlayers));
selectFixtureActivity.PutExtra("clickCount", clickCount);
holder.playerName.SetTextColor(mInflater.Context.Resources.GetColor(Resource.Drawable.white));
deletePlayer(position);
int po = itemPos.IndexOf(position);
itemPos.RemoveAt(po);
NotifyDataSetChanged();
class ViewHolder : Java.Lang.Object
{
public TextView playerName;
}
And my activity:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.SelectPlayer);
homeListAdapter = new HomePlayersAdapter(this);
listView = FindViewById<ListView>(Resource.Id.lvSelectPlayers);
TextView TeamSelect = FindViewById<TextView>(Resource.Id.tvSelectPlayer);
listView.Adapter = homeListAdapter;
listView.ChoiceMode = ChoiceMode.Multiple;
this.listView.ChoiceMode = ChoiceMode.Multiple;
var nameHome = Intent.GetStringExtra("nameHome");
var clickCount = Intent.GetStringExtra("clickCount");
TextView homeTeam = (TextView)FindViewById(Resource.Id.tvHomeTeam);
homeTeam.SetText(nameHome, Button.BufferType.Normal);
this.listView.ItemClick += (sender, e) =>
{
homeListAdapter.itemClick(e.Position);
}
I tried do that in different way: I send clickCount variable to the activity and there in ItemClick method i tried change the text view, but clickCount var on the begining is send to the acticity but when ItemClick method finish clickCount change value to null.How can i solve this problem?
You should not access the Activity directly from the Adapter. You should set a listener on the adapter (the listener can be the Activity). This is based on the Observer pattern. It decouples the components and promotes re-usability. Then the Activity, when called, can modify its own Text View.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
ListView myListView = (ListView)findViewById(R.id.your_list);
final TextView myTextView = (TextView)findViewById(R.id.your_text);
YourAdapter adapter = new YourAdapter();
adapter.setListener(new CustomListener() { // You write this method in your adapter
#Override
public void onItemClicked(Item clickedItem) {
myListView.setText( clickedItem.toString() );
}
});
}
Or if you aren't doing anything special in the custom adapter, you can always use the built in list view listener.
myListView.setOnItemClickListener( new OnItemClick() { // This is not onClick, but onItemClick
#Override
public void onItemClicked(AdapterView<?> parent, View view, int position, long id) {
Object clickedItem = parent.getItemAtPosition(position);
myTextView.setText( clickedItem.toString() );
}
});
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.