ViewPager not Loading Fragments when using TabLayout - xamarin.android

I got a simple layout with TabLayout and PageViewer but can't get them to work together
<com.google.android.material.tabs.TabLayout
android:id="#+id/sliding_tabs_emoji"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabMode="scrollable"
app:tabGravity="fill"
app:tabIndicatorColor="#color/gray"
app:tabIndicatorHeight="1dp"
android:paddingBottom="2dp"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager_emoji"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/red"/>
In my Activity OnCreate initializing the following
//Fragment array
var fragments = new AndroidX.Fragment.App.Fragment[]
{
Library.Fun.Emoji.Fragments.Recent.NewInstance(),
Library.Fun.Emoji.Fragments.People.NewInstance(),
};
//Tab title array
var titles = Android.Runtime.CharSequence.ArrayFromStringArray(new[] {
"Recent" ,
"People"
});
var viewPager = FindViewById<ViewPager>(Resource.Id.viewpager_emoji);
//viewpager holding fragment array and tab title text
viewPager.Adapter = new EmojiTabsPagerAdapter(SupportFragmentManager, fragments, titles);
// Give the TabLayout the ViewPager
TAB_Layout.SetupWithViewPager(viewPager);
Toast.MakeText(this, "SET", ToastLength.Short);
TAB_Layout.GetTabAt(0).SetIcon(Resource.Drawable.ic_camera);
TAB_Layout.GetTabAt(1).SetIcon(Resource.Drawable.ic_camera);
Where the Adapter is simple as it could be as following
public class EmojiTabsPagerAdapter : FragmentPagerAdapter
{
private readonly AndroidX.Fragment.App.Fragment[] fragments;
private readonly ICharSequence[] titles;
public EmojiTabsPagerAdapter(AndroidX.Fragment.App.FragmentManager fm, AndroidX.Fragment.App.Fragment[] fragments, ICharSequence[] titles) : base(fm)
{
this.fragments = fragments;
this.titles = titles;
}
public override int Count
{
get
{
return fragments.Length;
}
}
public override AndroidX.Fragment.App.Fragment GetItem(int position)
{
return fragments[position];
}
public override ICharSequence GetPageTitleFormatted(int position)
{
//return titles[position];
return null;
}
}
Tabs are appearing but Fragments are not loading, The results are the following
Where it should load RECENT and PEOPLE fragments on each tab, my Fragment XML is the following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="300dp"
android:background="#color/green">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="RECENTS"/>
</RelativeLayout>
And fragment's code is the following (for RECENT)
public class Recent : AndroidX.Fragment.App.Fragment
{
public static Recent NewInstance()
{
var frag = new Recent { Arguments = new Bundle() };
return frag;
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.fragment_emoji_recent, container, false);
return view;
}
}
Any Idea what am I doing wrong?

I use two Fragments: TabFragment1, TabFragment2 to test. In your code, you did provide the code about SetupWithViewPager.
The code below works well for me.
void setupViewPager(Android.Support.V4.View.ViewPager viewPager)
{
var adapter = new Adapter(SupportFragmentManager);
adapter.AddFragment(new TabFragment1(), "First Fragment");
adapter.AddFragment(new TabFragment2(), "Second Fragment");
viewPager.Adapter = adapter;
viewpager.Adapter.NotifyDataSetChanged();
//viewpager.OffscreenPageLimit(4);
}
In MainActivity, you could set like below.
var tabLayout = FindViewById<TabLayout>(Resource.Id.tabs);
tabLayout.SetupWithViewPager(viewpager);
You could download the source file from the link: https://www.c-sharpcorner.com/article/xamarin-android-create-viewpager-tablayout-floatingactionbutton-supportacti/

Did this work before moving to AndroidX?
I think you may need to pass ChildFragmentManager instead of FragmentManager to your PagerAdapter.

Related

AppBarLayout CollapsingToolbar how to disable expand on EditText click?

In my test app I disable expansion of AppBarLayout when it is collapsed (by scrolling RecycleView). I do that by adding addOnOffsetChangedListener to AppBarLayout.
However, when I click EditText it expands again but, I do not want it to expand.
How to disable the expansion of AppBarLayout when I click EditText?
I have put the whole code, so that everyone can copy/paste the code, create new project and test this fast.
Here is how the .gif looks
Here is XML code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/beachcroatia"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<LinearLayout
android:id="#+id/messages_linear_layout"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_gravity="bottom"
android:background="#E1F5FE"
android:orientation="horizontal"
tools:layout_editor_absoluteY="453dp">
<EditText
android:id="#+id/editText_messageBox"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:layout_weight="0.85"
android:hint="Enter a message"/>
<ImageView
android:id="#+id/messages_sendArrow"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0.15"
android:src="#drawable/ic_send_message_" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Here is full MainActivity code:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerChat;
private AdapterChat mAdapterChat;
CollapsingToolbarLayout collapsingToolbarLayout;
AppBarLayout appBarLayout;
ImageView sendMessageImageViewButton;
EditText editTextMessage;
private List<Message> messagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
appBarLayout = findViewById(R.id.app_bar_layout);
sendMessageImageViewButton = findViewById(R.id.messages_sendArrow);
editTextMessage = findViewById(R.id.editText_messageBox);
messagesList = new ArrayList<>();
messagesList.addAll(getMessagesList());
mRecyclerChat = findViewById(R.id.recycleView);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerChat.setLayoutManager(manager);
mAdapterChat = new AdapterChat(this, messagesList);
mRecyclerChat.setAdapter(mAdapterChat);
//move to the last item in recycleview
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
editTextMessage.requestFocus();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
//sending new message and updating recycleview
sendMessageImageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Message Send", Toast.LENGTH_SHORT).show();
mAdapterChat.updateLastMessage(new Message(editTextMessage.getText().toString()));
editTextMessage.getText().clear();
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
}
});
}
//ading some items to a list
private List<Message> getMessagesList() {
List<Message> mMessages = new ArrayList<>();
for (int i = 0; i < 200; i++) {
mMessages.add(new Message("message " + i));
}
return mMessages;
}
}
Here is my message class where i add dummy data to show in RecycleView
public class Message {
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here is RecycleView Adapter code:
package com.example.petar.collapsingtolbartestiramo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AdapterChat extends RecyclerView.Adapter<AdapterChat.ChatHolder> {
private LayoutInflater mInflater;
private List<Message> messagesObekt;
public AdapterChat(Context context, List<Message> listOfMassages) {
mInflater = LayoutInflater.from(context);
messagesObekt = new ArrayList<>();
messagesObekt.addAll(listOfMassages);
notifyDataSetChanged();
}
public void updateChat(List<Message> porukeObjekt){
this.messagesObekt.addAll(porukeObjekt);
notifyDataSetChanged();
}
public void updateLastMessage(Message porukeObjekt) {
this.messagesObekt.add(porukeObjekt);
//notifyDataSetChanged();
notifyItemInserted(messagesObekt.size());
}
public List<Message> getMessagesObekt() {
return messagesObekt;
}
#Override
public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_message, parent, false);
ChatHolder holder = new ChatHolder(view, messagesObekt);
return holder;
}
#Override
public void onBindViewHolder(ChatHolder holder, int position) {
holder.textViewMessage.setText(messagesObekt.get(position).getMessage());
}
#Override
public int getItemCount() {
return messagesObekt.size();
}
public static class ChatHolder extends RecyclerView.ViewHolder {
TextView textViewMessage;
public ChatHolder(View itemView, List<Message> messagesObekt) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.rv_message);
}
}
}
Here is RecycleView item XML code (list_message.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/rv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Poruka Ovdje"
android:textSize="14sp"/>
</LinearLayout>
:
EDIT
I tried adding focus listener to EditText but, that did not helped. This is how i try:
editTextMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
appBarLayout.setExpanded(false);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
}
}
});
I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
There is indeed a better, cleaner and simpler solution.
The culprit that leads to this "issue" is actually a feature that was added by Google inside AppBarLayout.ScrollingViewBehavior. That's the one you set via app:layout_behavior="#string/appbar_scrolling_view_behavior". Inside that class, onRequestChildRectangleOnScreen calls setExpanded(false, !immediate) whenever the keyboard is shown. You simply override this method and return false to disable this default behavior. Add this class to your project:
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.appbar.AppBarLayout;
public class FixedScrollingViewBehavior extends AppBarLayout.ScrollingViewBehavior {
public FixedScrollingViewBehavior() {
super();
}
public FixedScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onRequestChildRectangleOnScreen(#NonNull CoordinatorLayout parent,
#NonNull View child, #NonNull Rect rectangle, boolean immediate) {
return false;
}
}
Then just use this new class by changing app:layout_behavior="#string/appbar_scrolling_view_behavior" to app:layout_behavior="your.source.package.FixedScrollingViewBehavior".
I have find the answer. I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
So, what i done is i put the whole AppBarLayout params to 0 when i click EditText or when EditText get focus.
So, when EditText is clicked, AppBarLayout is still there but, now his height is 0 and it is not visible.
This do the trick:
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0)
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
Also, if you want to have expand option, you need to save height of previous params and then just add that height again.
So, this is a code how i done it:
Fist, when i scroll RecycleView i disable expand of appBarLayout using addOnOffsetChangedListener. However i also save params height for future use.
int sizeParams; //save params height
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding and scroll
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
//saving height for future use
sizeParams = params.height;
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
Now i make this 2 method which i call when i need expand/collaps.
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
sizeParams = params.height;//save params height for future use
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
//Expand AppBarLayout
public void expandAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 3*sizeParams; // HEIGHT
appBarLayout.setLayoutParams(params); //add height to appbarlayout
//enable scroll and expand
AppBarLayout.LayoutParams params1 = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params1.setScrollFlags(1);
appBarLayout.setExpanded(true);//expand
}

RecyclerView in Fragment of ViewPager results in InflateException

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

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

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

Xamarin.Android NavigationTabStrip

I want to implement the NavigationTabStrip (https://github.com/martijn00/NavigationTabStripXamarin) to my app, but I don't know how. I've seen also the original project, but I'm new in this world. Has anyone a project to help me to implement this? Or is there anyone that knows how to do that? I'm trying to create a TabLayout in material design.
The Easiest way to do it would be like this :
http://camposha.info/source/xamarin-android-swipe-tabs-viewpager-fragments-images-actionbartabs/
http://www.c-sharpcorner.com/article/creating-sliding-tab-layout-interface-using-xamarin-android-using-visual-studio/
The code is in xamarin so it would be an easy implementation for you!
Goodluck!
UPDATE:
The code for your activities Axml file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/MyTheme"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
/>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Code for your Activities cs file:
public class GoogleMapsActivity : AppCompatActivity
{
private Fragment MapsFragment;
private Fragment ListFragment;
private TabLayout allTabs;
FragmentManager fm;
FragmentTransaction ft;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.your_activity);
bindAllWidgets();
setupTabLayout();
setUpToolbar();
}
void setUpToolbar()
{
#region "Tool bar"
var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.SetTitleTextColor(ResourcesCompat.GetColor(Resources, Resource.Color.colorRedText, null));
Drawable upArrow = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.abc_ic_ab_back_mtrl_am_alpha, null);
upArrow.SetColorFilter(Color.ParseColor(Resources.GetString(Resource.Color.colorRedText)), PorterDuff.Mode.SrcAtop);
SetSupportActionBar(toolbar);
SupportActionBar.Title = Resources.GetString(Resource.String.toolbar_title_dhl_service_points);
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayHomeAsUpEnabled(true);
SupportActionBar.SetHomeAsUpIndicator(upArrow);
#endregion
}
private void setupTabLayout()
{
allTabs.AddTab(allTabs.NewTab().SetText(Resources.GetString(Resource.String.google_maps_page_title_map)), true);
allTabs.AddTab(allTabs.NewTab().SetText(Resources.GetString(Resource.String.google_maps_page_title_list)));
}
private void bindAllWidgets()
{
allTabs = FindViewById<TabLayout>(Resource.Id.tabs);
allTabs.TabSelected += AllTabs_TabSelected;
}
private void AllTabs_TabSelected(object sender, TabSelectedEventArgs e)
{
var tab = e.Tab;
setCurrentTabFragment(tab.Position);
}
public void replaceFragment(Fragment fragment)
{
fm = FragmentManager;
ft = fm.BeginTransaction();
if (fragment == MapsFragment)
{
if (MapsFragment == null)
{
MapsFragment = new PoSLocationMapView(this);
ft.Add(Resource.Id.frame_container, MapsFragment, "MapsFragment");
}
else
{
ft.Detach(FragmentManager.FindFragmentByTag("ListFragment"));
ft.Attach(MapsFragment);
}
}
else if (fragment == ListFragment)
{
if (ListFragment == null)
{
ListFragment = new ServicePointDHLList(this);
ft.Add(Resource.Id.frame_container, ListFragment, "ListFragment");
}
else
{
ft.Detach(FragmentManager.FindFragmentByTag("MapsFragment"));
ft.Attach(ListFragment);
}
}
ft.SetTransition(FragmentTransit.FragmentOpen);
ft.Commit();
}
private void setCurrentTabFragment(int tabPosition)
{
switch (tabPosition)
{
case 0:
replaceFragment(MapsFragment);
break;
case 1:
replaceFragment(ListFragment);
break;
}
}
}
Try this library it is more clearly.
https://github.com/ahoefling/TabStrip/blob/master/README.md

How to overlay google place auto complete fragment in map fragment in xamarin android?

I am working in Xamarin android, i want to show google place autocomplete fragment in google map fragment, am using this below code but it getting error, anyone can help to solve this?
Android.Views.InflateException: Binary XML file line #1: Error
inflating class fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/googlemap"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment">
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" />
</fragment>
</LinearLayout>
namespace test
{
[Activity(Label = "CommuteX", MainLauncher = true, Icon = "#mipmap/icon", Theme = "#android:style/Theme.Holo.Light.NoActionBar.Fullscreen")]
public class MainActivity : FragmentActivity, IOnMapReadyCallback, IPlaceSelectionListener, IOnConnectionFailedListener
{
private GoogleMap GMap;
public void OnConnectionFailed(ConnectionResult result)
{
throw new NotImplementedException();
}
public void OnError(Statuses status)
{
Log.Info("xamarin", "An error occurred: " + status);
}
public void OnMapReady(GoogleMap googleMap)
{
this.GMap = googleMap;
LatLng latlng = new LatLng(Convert.ToDouble(12.733027), Convert.ToDouble(77.83016));
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng, 15);
GMap.MoveCamera(camera);
MarkerOptions options = new MarkerOptions().SetPosition(latlng).SetTitle("Hosur");
GMap.AddMarker(options);
}
public void OnPlaceSelected(IPlace place)
{
var placeadd = place.AddressFormatted;
var placename = place.NameFormatted;
var namadd = placename + "," + placeadd;
var latlng = place.LatLng;
Log.Info("xamarin", "Place: " + namadd);
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
SetUpMap();
var mGoogleApiClient = new GoogleApiClient
.Builder(this)
.AddApi(PlacesClass.GEO_DATA_API)
.AddApi(PlacesClass.PLACE_DETECTION_API)
.EnableAutoManage(this, this)
.Build();
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)FragmentManager.FindFragmentById(Resource.Id.place_autocomplete_fragment);
autocompleteFragment.SetOnPlaceSelectedListener(this);
}
private void SetUpMap()
{
if (GMap == null)
{
FragmentManager.FindFragmentById<MapFragment>(Resource.Id.googlemap).GetMapAsync(this);
}
}
}
}

Resources