android expandableListView animate slide up? - android-animation

I want to animate slide down and slide up on expandablelistview when I click the groupItem.Then I have finish the slide down.
public class ExpandAnimation extends Animation {
private static final String TAG = "ExpandAnimation";
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;
/**
* Initialize the animation
* #param view The layout we want to animate
* #param duration The duration of the animation, in ms
*/
public ExpandAnimation(View view, int duration) {
setDuration(duration);
mAnimatedView = view;
mViewLayoutParams = (LayoutParams) view.getLayoutParams();
// if the bottom margin is 0,
// then after the animation will end it'll be negative, and invisible.
mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
mMarginStart = mViewLayoutParams.bottomMargin;
Log.i(TAG, "mMarginStart:>>>>>>>"+mMarginStart);
mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
Log.i(TAG, "mMarginEnd:>>>>>>>"+mMarginEnd);
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
Log.i(TAG, "applyTransformation-->"+interpolatedTime);
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart
+ (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout();
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd;
mAnimatedView.requestLayout();
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.GONE);
}
mWasEndedAlready = true;
}
}
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Log.i(TAG, "getChildView");
#SuppressWarnings("unchecked")
String text = ((Map<String, String>) getChild(groupPosition,
childPosition)).get("child");
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child, null);
}
View toolbar = convertView.findViewById(R.id.toolbar);
setAnimationView(toolbar);
((LinearLayout.LayoutParams) toolbar.getLayoutParams()).bottomMargin = -75;
toolbar.setVisibility(View.GONE);
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 1000);
toolbar.startAnimation(expandAni);
TextView tv = (TextView) convertView.findViewById(R.id.childTo);
tv.setText(text);
return convertView;
}
But when I click the groupItem to collapse the group,it doesn't call the getChildView() method.So how can I to call the getChildView() and let it slide up?

I believe that you want to extend BaseExpandableListAdapter if you want to call (or #Override) getChildView.
http://developer.android.com/reference/android/widget/BaseExpandableListAdapter.html

Related

spinner selected value returns to old value when recyclerview row is clicked

i have created an android application using xamarin.android. the application has a recyclerview that contains a spinner. what i want is when the user selects an item from the spinner, i need to change the value of the corresponding column and row in the datatable and i need the new value to be displayed in the spinner in the recyclerview in the row where the spinner value is selected. the problem is that whenever a value is selected, when another row is clicked, the old value of the spinner is displayed. i tried a lot of ways like the code in the following link: https://www.codeproject.com/articles/1033283/android-recycler-view-with-spinner-item-change-sel, but it didn't work. this is my code:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, laborname;
public EditText overtime;
public LinearLayout linearLayout;
public Spinner days;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
laborname = itemView.FindViewById<TextView>(Resource.Id.laborname);
days = itemView.FindViewById<Spinner>(Resource.Id.days);
overtime = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
// public event EventHandler<AdapterView.ItemSelectedEventArgs> SpinnerItemSelectionChanged;
public static DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_schedule context;
public static int selected_pos = -1;
RecyclerView recyclerView;
FloatingActionButton delete;
public recyclerviewAdapter(new_schedule context, DataTable sum_req, RecyclerView recyclerView)
{
this.context = context;
summary_Requests = sum_req;
this.recyclerView = recyclerView;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_new_schedule_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.days.ItemSelected += (sender, e) =>
{
Spinner spinner = (Spinner)sender;
int position = Convert.ToInt32(spinner.Tag);
summary_Requests.Rows[position]["dayNbr"] = Convert.ToDecimal(spinner.GetItemAtPosition(e.Position).ToString());
};
vh.overtime.TextChanged += (sender, e) =>
{
if (vh.overtime.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["overtimeHours"] = Convert.ToInt32(vh.overtime.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("unit must be integer not decimal", icon);
user.zero_val = "exits";
}
else if (vh.overtime.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.overtime.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.laborname.Text = summary_Requests.Rows[position]["laborerName"].ToString();
List<decimal> days_data = new List<decimal>();
days_data.Add((decimal)0.5);
days_data.Add((decimal)1);
var adapter = new ArrayAdapter(this.context.Context, Android.Resource.Layout.SimpleSpinnerItem, days_data);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.days.Tag = position;
vh.days.Adapter = adapter;
vh.days.SetSelection(1);
vh.overtime.Text = summary_Requests.Rows[position]["overtimeHours"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
vh.ItemView.Click += (sender, e) =>
{
int pos = vh.LayoutPosition;
user.del_pos = position;
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
//delete.Click += delegate
//{
// vh.days.Enabled = false;
//};
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override long GetItemId(int position)
{
return position;
}
public void deleteItem(int index)
{
summary_Requests.Rows.RemoveAt(index);
NotifyItemRemoved(index);
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
}
}
I read the article that you provide, you need to do two things when you change spinner value, firstly, you need to change vegeList's itemPosition quantity by SpinnerItemSelectionChangedEvent, then you need to update TotalAmount in OnBindViewHolder
private void SpinnerItemSelectionChangedEvent(object sender, AdapterView.ItemSelectedEventArgs e)
{
Spinner spinner = (Spinner)sender;
var itemPosition = Convert.ToInt32(spinner.Tag);
//Update the view by Total Amount, after spinner value is been selected.
var currentquantity = vegeList[itemPosition].Quantity;
var selectedQuantity = Convert.ToInt32(spinner.GetItemAtPosition(e.Position).ToString());
if (currentquantity != selectedQuantity)
{
vegeList[itemPosition].Quantity = selectedQuantity;
Madapter.NotifyItemChanged(itemPosition);
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
var item = Items[position];
var vh = holder as VegeViewHolder;
var spinnerPos = 0;
var adapter = new ArrayAdapter<String>(Context, Android.Resource.Layout.SimpleSpinnerItem, _quantity);
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
vh.Name.Text = item.Name;
vh.Price.Text = string.Format("Price: ${0}", item.Price);
vh.ItemView.Tag = position;
if (item.Quantity > 0)
{
spinnerPos = adapter.GetPosition(item.Quantity.ToString());
vh.TotalAmount.Text = string.Format("${0}", item.Price * item.Quantity);
}
else
{
vh.TotalAmount.Text = "";
}
vh.Quantity.Tag = position; //keep reference to list view row position
vh.Quantity.Adapter = adapter;
vh.Quantity.SetSelection(spinnerPos);
vh.Image.SetImageResource(item.ImageId);
}

How to show a badges count of ToolBarItem Icon in Xamarin Forms

It is not about how to show notification badges nor it's about to show toolbar item icon. It is clear question that how to show a badges count on a toolbar item icon. ?
I am sharing code to create ToolbarItem with icon in XF content page:
In cs File:
ToolbarItem cartItem = new ToolbarItem();
scanItem.Text = "My Cart";
scanItem.Order = ToolbarItemOrder.Primary;
scanItem.Icon = "carticon.png";
ToolbarItems.Add(cartItem );
In Xaml File:
<ContentPage.ToolbarItems>
<ToolbarItem Text="Cart" Priority="0" x:Name="menu1">
</ToolbarItem>
</ContentPage.ToolbarItems>
Now I want to Place a badge count on the above added tool bar item icon. How it can be achieved ?
Placing badge icon's in the native toolbars is actually more effort than its worth. If I need a badge icon, I remove the navigation page.
NavigationPage.SetHasNavigationBar(myPageInstance, false);
Then I create my own toolbar from scratch. In this toolbar, I can overlay an image in there, you can also place a number in it as needed. For example.
<Grid>
<Grid.GestureRecognizers>
<TapGestureRecognizer Command="{Binding IconCommand}" />
</Grid.GestureRecognizers>
<iconize:IconImage
Icon="fa-drawer"
IconColor="white"
IconSize="20" />
<Grid Margin="15,-15,0,0">
<iconize:IconImage Grid.Row="0"
HeightRequest="40"
WidthRequest="40"
Icon="fa-circle"
IconColor="red"
IsVisible="{Binding IsCircleVisible}"
IconSize="10" />
</Grid>
</Grid>
I use Iconize wtih FontAwesome for the icons
With the help of Xamarin Forum Discussion, I have achieved it. Read ad understand the complete discussion before implement it. Thank you "Slava Chernikoff", "Emanuele Sabetta", "Mirza Sikander", "Satish" to discuss and yours share code.
Setp 1: Create a Helper Class in PCL and install NGraphics package from nugget.
public class CartIconHelper
{
private static Graphic _svgGraphic = null;
public const string ResourcePath = "ToolBarAndroidBadge.Resources.cartIcon.svg";
private static PathOp[] RoundRect(NGraphics.Rect rect, double radius)
{
return new PathOp[]
{
new NGraphics.MoveTo(rect.X + radius, rect.Y),
new NGraphics.LineTo(rect.X + rect.Width - radius, rect.Y),
new NGraphics.ArcTo(new NGraphics.Size(radius, radius), true, false, new NGraphics.Point(rect.X + rect.Width, rect.Y + radius)),
new NGraphics.LineTo(rect.X + rect.Width, rect.Y + rect.Height - radius),
new NGraphics.ArcTo(new NGraphics.Size(radius, radius), true, false, new NGraphics.Point(rect.X + rect.Width - radius, rect.Y + rect.Height)),
new NGraphics.LineTo(rect.X + radius, rect.Y + rect.Height),
new NGraphics.ArcTo(new NGraphics.Size(radius, radius), true, false, new NGraphics.Point(rect.X, rect.Y + rect.Height - radius)),
new NGraphics.LineTo(rect.X, rect.Y + radius), new NGraphics.ArcTo(new NGraphics.Size(radius, radius), true, false, new NGraphics.Point(rect.X + radius, rect.Y)),
new NGraphics.ClosePath()
};
}
public static string DrawCartIcon(int count, string path, double iconSize = 30, double scale = 2, string fontName = "Arial", double fontSize = 12, double textSpacing = 4)
{
var service = DependencyService.Get<IService>();
var canvas = service.GetCanvas();
if (_svgGraphic == null) using (var stream = typeof(CartIconHelper).GetTypeInfo().Assembly.GetManifestResourceStream(path))
_svgGraphic = new SvgReader(new StreamReader(stream)).Graphic;
//st = ReadFully(stream);
var minSvgScale = Math.Min(canvas.Size.Width / _svgGraphic.Size.Width, canvas.Size.Height / _svgGraphic.Size.Height) / 1.15;
var w = _svgGraphic.Size.Width / minSvgScale;
var h = _svgGraphic.Size.Height / minSvgScale;
_svgGraphic.ViewBox = new NGraphics.Rect(0, -14, w, h);
_svgGraphic.Draw(canvas);
if (count > 0)
{
var text = count > 99 ? "99+" : count.ToString();
var font = new NGraphics.Font(fontName, fontSize);
var textSize = canvas.MeasureText(text, font);
var textRect = new NGraphics.Rect(canvas.Size.Width - textSize.Width - textSpacing, textSpacing, textSize.Width, textSize.Height);
if (count < 10)
{
var side = Math.Max(textSize.Width, textSize.Height);
var elipseRect = new NGraphics.Rect(canvas.Size.Width - side - 2 * textSpacing, 0, side + 2 * textSpacing, side + 2 * textSpacing);
canvas.FillEllipse(elipseRect, NGraphics.Colors.Red);
textRect -= new NGraphics.Point(side - textSize.Width, side - textSize.Height) / 2.0;
}
else
{
var elipseRect = new NGraphics.Rect(textRect.Left - textSpacing, textRect.Top - textSpacing, textRect.Width + 2 * textSpacing, textSize.Height + 2 * textSpacing);
canvas.FillPath(RoundRect(elipseRect, 6), NGraphics.Colors.Red);
}
var testReact1= new NGraphics.Rect(20,12,0,0);
// canvas.DrawText(text, textRect + new NGraphics.Point(0, textSize.Height), font, NGraphics.TextAlignment.Center, NGraphics.Colors.Black);
canvas.DrawText("5", testReact1, font, NGraphics.TextAlignment.Left, NGraphics.Colors.White);
}
service.SaveImage(canvas.GetImage());
string imagePath = service.GetImage();
return imagePath;
// return st;
}
}
Step 2: Create a interface to IService in PCL
public interface IService
{
IImageCanvas GetCanvas();
void SaveImage(NGraphics.IImage image);
string GetImage();
}
Step 3 : Implement this interface in your Android project
class CanvasServices:IService
{
private readonly AndroidPlatform _platform;
public CanvasServices()
{
_platform = new AndroidPlatform();
}
public void SaveImage(IImage image)
{
var dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(dir, "cart.png");
var stream = new FileStream(filePath, FileMode.Create);
image.SaveAsPng(stream);
//bitmap.Compress(image., 100, stream);
stream.Close();
}
public string GetImage()
{
var dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filePath = System.IO.Path.Combine(dir, "cart.png");
using (var streamReader = new StreamReader(filePath))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}
return filePath;
}
public IImageCanvas GetCanvas()
{
NGraphics.Size size = new NGraphics.Size(30);
return _platform.CreateImageCanvas(size);
}
public NGraphics.AndroidPlatform GetPlatform()
{
return _platform;
}
}
Setp 4: Now, use CartIcon Helper in your PCL project to show badges in TabBarItem.
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var imagePath = CartIconHelper.DrawCartIcon(2, "ToolBarAndroidBadge.Resources.cartIcon.svg");
string deviceSepecificFolderPath = Device.OnPlatform(null, imagePath, null);
object convertedObject = new FileImageSourceConverter().ConvertFromInvariantString(deviceSepecificFolderPath);
FileImageSource fileImageSource = (FileImageSource)convertedObject;
ToolbarItem cartItem = new ToolbarItem();
cartItem.Text = "My Cart";
cartItem.Order = ToolbarItemOrder.Primary;
cartItem.Icon = fileImageSource;
ToolbarItems.Add(cartItem);
}
}
For any one who wants to add badge on toolbar item using custom ui try,
Instead of using default toolbar item, you can hide the default navigation bar by NavigationPage.SetHasNavigationBar(this, false);
in the constructor.
Then prepare the custom navigation bar with toolbar item with badge as mentioned in above answers.
If you are using master detail page, hiding default navigation bar will hide hamburger icon, so need to slide from left to see sliding menu. Alternate method would be place a button with hamburger icon in custom navigation bar, on button click use messaging center to present the sliding menu.
Example: On page in which hamburger button is clicked
private void Button_Clicked(object sender, System.EventArgs e)
{
MessagingCenter.Send(this, "presnt");
}
On MasterDetail page
MessagingCenter.Subscribe<YourPage>(this, "presnt", (sender) =>
{
IsPresented = true;
});
Before making IsPresented=true, check for sliding menu is not all-ready presented.
Check https://github.com/LeslieCorrea/Xamarin-Forms-Shopping-Cart for badge on toolbar item.
Implement below code to draw a ground circle with text over toolbar icon
BarButtonItemExtensions.cs
using CoreAnimation;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using UIKit;
namespace TeamCollaXform.Views.Services
{
public static class BarButtonItemExtensions
{
enum AssociationPolicy
{
ASSIGN = 0,
RETAIN_NONATOMIC = 1,
COPY_NONATOMIC = 3,
RETAIN = 01401,
COPY = 01403,
}
static NSString BadgeKey = new NSString(#"BadgeKey");
[DllImport(Constants.ObjectiveCLibrary)]
static extern void objc_setAssociatedObject(IntPtr obj, IntPtr key, IntPtr value, AssociationPolicy policy);
[DllImport(Constants.ObjectiveCLibrary)]
static extern IntPtr objc_getAssociatedObject(IntPtr obj, IntPtr key);
static CAShapeLayer GetBadgeLayer(UIBarButtonItem barButtonItem)
{
var handle = objc_getAssociatedObject(barButtonItem.Handle, BadgeKey.Handle);
if (handle != IntPtr.Zero)
{
var value = ObjCRuntime.Runtime.GetNSObject(handle);
if (value != null)
return value as CAShapeLayer;
else
return null;
}
return null;
}
static void DrawRoundedRect(CAShapeLayer layer, CGRect rect, float radius, UIColor color, bool filled)
{
layer.FillColor = filled ? color.CGColor : UIColor.White.CGColor;
layer.StrokeColor = color.CGColor;
layer.Path = UIBezierPath.FromRoundedRect(rect, radius).CGPath;
}
public static void AddBadge(this UIBarButtonItem barButtonItem, string text, UIColor backgroundColor, UIColor textColor, bool filled = true, float fontSize = 11.0f)
{
if (string.IsNullOrEmpty(text))
{
return;
}
CGPoint offset = CGPoint.Empty;
if (backgroundColor == null)
backgroundColor = UIColor.Red;
var font = UIFont.SystemFontOfSize(fontSize);
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
font = UIFont.MonospacedDigitSystemFontOfSize(fontSize, UIFontWeight.Regular);
}
var view = barButtonItem.ValueForKey(new NSString(#"view")) as UIView;
var bLayer = GetBadgeLayer(barButtonItem);
bLayer?.RemoveFromSuperLayer();
var badgeSize = text.StringSize(font);
var height = badgeSize.Height;
var width = badgeSize.Width + 5; /* padding */
//make sure we have at least a circle
if (width < height)
{
width = height;
}
//x position is offset from right-hand side
var x = view.Frame.Width - width + offset.X;
var badgeFrame = new CGRect(new CGPoint(x: x - 4, y: offset.Y + 5), size: new CGSize(width: width, height: height));
bLayer = new CAShapeLayer();
DrawRoundedRect(bLayer, badgeFrame, 7.0f, backgroundColor, filled);
view.Layer.AddSublayer(bLayer);
// Initialiaze Badge's label
var label = new CATextLayer();
label.String = text;
label.TextAlignmentMode = CATextLayerAlignmentMode.Center;
label.SetFont(CGFont.CreateWithFontName(font.Name));
label.FontSize = font.PointSize;
label.Frame = badgeFrame;
label.ForegroundColor = filled ? textColor.CGColor : UIColor.White.CGColor;
label.BackgroundColor = UIColor.Clear.CGColor;
label.ContentsScale = UIScreen.MainScreen.Scale;
bLayer.AddSublayer(label);
// Save Badge as UIBarButtonItem property
objc_setAssociatedObject(barButtonItem.Handle, BadgeKey.Handle, bLayer.Handle, AssociationPolicy.RETAIN_NONATOMIC);
}
public static void UpdateBadge(this UIBarButtonItem barButtonItem, string text, UIColor backgroundColor, UIColor textColor)
{
var bLayer = GetBadgeLayer(barButtonItem);
if (string.IsNullOrEmpty(text) || text == "0")
{
bLayer?.RemoveFromSuperLayer();
objc_setAssociatedObject(barButtonItem.Handle, BadgeKey.Handle, new CAShapeLayer().Handle, AssociationPolicy.ASSIGN);
return;
}
var textLayer = bLayer?.Sublayers?.First(p => p is CATextLayer) as CATextLayer;
if (textLayer != null)
{
textLayer.String = text;
}
else
{
barButtonItem.AddBadge(text, backgroundColor, textColor);
}
}
}
}
ToolbarItemBadgeService.cs
using TeamCollaXform.Views.Services;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: Dependency(typeof(ToolbarItemBadgeService))]
namespace TeamCollaXform.Views.Services
{
/// <summary>
///
/// </summary>
public interface IToolbarItemBadgeService
{
void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor);
}
/// <summary>
///
/// </summary>
public class ToolbarItemBadgeService : IToolbarItemBadgeService
{
public void SetBadge(Page page, ToolbarItem item, string value, Color backgroundColor, Color textColor)
{
Device.BeginInvokeOnMainThread(() =>
{
var renderer = Platform.GetRenderer(page);
if (renderer == null)
{
renderer = Platform.CreateRenderer(page);
Platform.SetRenderer(page, renderer);
}
var vc = renderer.ViewController;
var rightButtomItems = vc?.ParentViewController?.NavigationItem?.RightBarButtonItems;
var idx = rightButtomItems.Length - page.ToolbarItems.IndexOf(item) - 1; //Revert
if (rightButtomItems != null && rightButtomItems.Length > idx)
{
var barItem = rightButtomItems[idx];
if (barItem != null)
{
barItem.UpdateBadge(value, backgroundColor.ToUIColor(), textColor.ToUIColor());
}
}
});
}
}
}
Usage
void OnAttachClicked(object sender, EventArgs e)
{
//var answer = await DisplayAlert("Question?", "Would you like to play a game", "Yes", "No");
//Debug.WriteLine("Answer: " + answer);
ToolbarItem cmdItem = sender as ToolbarItem;
DependencyService.Get<IToolbarItemBadgeService>().SetBadge(this, cmdItem, $"2", Color.DarkOrange, Color.White);
}
Links: 1) for instruction and 2) for sample code
https://www.xamboy.com/2018/03/08/adding-badge-to-toolbaritem-in-xamarin-forms/
https://github.com/CrossGeeks/ToolbarItemBadgeSample

how to add text and textsize as selected size from spinner on canvas android?

i set text and textsize from edittextbox i get perfect size as i selected but whenever i set different textsize for another text it takes same textsize for both text as second textsize...i want text as selected textsize form spinner...help...
Thank u in advance
here is my code of alertdialogbox and spinner `
LayoutInflater linf = LayoutInflater.from(c_new);
final View inflator = linf.inflate(R.layout.dialog, null);
AlertDialog.Builder alert = new AlertDialog.Builder(c_new);
alert.setTitle("EditText");
alert.setView(inflator);
final EditText editText = (EditText) inflator.findViewById(R.id.editTextResult);
alert.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
srt=editText.getText().toString();
c.setEdittext(srt);
click_values c1 = new click_values();
c1.setImage(3);
dialog.cancel();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
final Spinner spinner = (Spinner)inflator.findViewById(R.id.mySpinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item,textSize);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
c.setTextsize(Float.parseFloat(item));
spinner.setPrompt("Select Text Size");
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected Text Size: " + item, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
spinner.setPrompt("Title");
}
});
here is the code for set and get edittext and textsize`
static String Edittext;
public static String getEdittext() {
return Edittext;
}
public static String setEdittext(String edittext) {
click_values.Edittext = edittext;
Edittext = edittext;
return edittext;
}
static float textsize;
public static float getTextsize() {
return textsize;
}
public static void setTextsize(float textsize) {
click_values.textsize = textsize;
}
here i how i store text and textsize `
ArrayList<EdtText> editTexts = new ArrayList<EdtText>();
ArrayList<Integer> textsize = new ArrayList<Integer>();
if (text_c == 0 && c.getImage() == 4) {
mPaint.setTextSize(c.getTextsize());
mPaint.setStyle(Style.FILL);
canvas.drawText(c.getEdittext(), startX, startY, mPaint);
c.setImage(0);
} else if (c.getImage() == 4) {
editTexts.add(new EdtText(c.getEdittext(), startX, startY));
mPaint.setTextSize(c.getTextsize());
mPaint.setStyle(Style.FILL);
canvas.drawText(c.getEdittext(), startX, startY, mPaint);
c.setImage(0);
text_c = 0;
}
for (EdtText l : editTexts) {
canvas.drawText(l.EdtText1, l.startX, l.stopY, mPaint);
}
}

Getting Sprite to fade back in after fade out? Entitiy Modifier

Hi im trying to get a sprite to fade in and scale up after fading out and scaling down. For this i used an Entitiy modifier listener but its not working? Heres my code:
public class GameScene {
Scene gameScene;
Engine engine;
Activity activity;
BitmapTextureAtlas mTextureAtlas;
ITextureRegion X;
ITextureRegion O;
ITextureRegion XO;
FadeInModifier fadeIn = new FadeInModifier(2);
FadeOutModifier fadeOut = new FadeOutModifier(2);
ScaleModifier scaleDown = new ScaleModifier(3, 1, 0);
ScaleModifier scaleUp = new ScaleModifier(2, 0, 1);
Sprite XOsprite;
Random rand = new Random();
boolean XYset = false;
public GameScene(Engine eng, Activity act) {
engine = eng;
activity = act;
}
public Scene getScene() {
gameScene = new Scene();
gameScene.setBackground(new Background(0, 256, 59));
int x = 0, y = 0;
if (rand.nextInt(2) == 0) {
XO = X;
} else {
XO = O;
}
if (!XYset) {
x = rand.nextInt(MainActivity.CAM_WIDTH);
y = rand.nextInt(MainActivity.CAM_HEIGHT);
XYset = true;
}
XOsprite = new Sprite(x, y, XO, engine.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent te, final float xVal,
final float yVal) {
XOsprite.registerEntityModifier(fadeOut);
XOsprite.registerEntityModifier(scaleDown);
return true;
}
};
IEntityModifierListener fadeOutListener = new IEntityModifierListener() {
#Override
public void onModifierStarted(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
}
#Override
public void onModifierFinished(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
XOsprite.clearEntityModifiers();
XOsprite.setPosition(rand.nextInt(MainActivity.CAM_WIDTH), rand.nextInt(MainActivity.CAM_HEIGHT));
XOsprite.registerEntityModifier(fadeIn);
XOsprite.registerEntityModifier(scaleUp);
}
};
fadeOut.addModifierListener(fadeOutListener);
XOsprite.registerEntityModifier(scaleUp);
XOsprite.registerEntityModifier(fadeIn);
gameScene.attachChild(XOsprite);
gameScene.registerTouchArea(XOsprite);
return gameScene;
}
The sprite just fades out and nothing happens. I also want the sprite to change to a random position on the screen when it fades back in. Help?
If you want to do fade in and scale in parallel then you can use use parallelEntityModifier.
Similarly for fade out and scale out parallel then you can use use parallelEntityModifier.
To run these two in sequence use SequenceEntityModifier.
Try this it will work.

JPanel not updating when my ArrayList of GamePieces changes

I have a simple game that is in progress. As of right now all I want to do is click the green button and have the fifth and third pieces switch places. The paintComponent is called after the swap in the arraylist is made, but the JPanel is not refreshed to show these changes. When i am running my application I am choosing 4 for the pieces for each side. Thus, the inner green and black pieces should change place. Please help.
Number1.java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.Container;
public class Number1 {
private static JButton greenButton,blackButton,newGameButton,inputButton;
private static JTextFieldNumber inputField;
static MyActionListen actionListen;
static Number1 myGame;
static JFrame myDialog,myFrame;
static DrawGamePieces gamePanel;
public int piecesPerSide = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
myGame = new Number1();
actionListen = new MyActionListen();
myGame.getStartingTokensValue();
System.out.println(Color.WHITE.toString());
}
private void makeComponents()
{
//Setting up the green button click
greenButton = new JButton("Green");
greenButton.setBounds(40, 0 , 100, 40);
greenButton.setForeground(Color.GREEN);
greenButton.addActionListener(actionListen);
//Setting up the black button click
blackButton = new JButton("Black");
blackButton.setBounds(greenButton.getLocation().x + greenButton.getWidth() + 10
, 0 , 100, 40);
blackButton.setForeground(Color.BLACK);
blackButton.addActionListener(actionListen);
//Setting up the new game button click
newGameButton = new JButton("New Game");
newGameButton.setBounds(blackButton.getLocation().x + blackButton.getWidth() + 10
, 0 , 100, 40);
newGameButton.setForeground(Color.BLUE);
newGameButton.addActionListener(actionListen);
//init gamePanel
gamePanel = new DrawGamePieces(myGame.piecesPerSide,myFrame.getSize().width, myFrame.getSize().height - 40);
gamePanel.setLocation(0, 40);
gamePanel.setBackground(Color.YELLOW);
}
private void makeGameFrame()
{
myFrame = new JFrame();
if(myGame.piecesPerSide <= 10) myFrame.setSize(400, 250);
else myFrame.setSize(600, 250);
myFrame.setLocation(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
myFrame.setTitle("Solitary Game"); //sets the title of the window
Container mainFrameContents = myFrame.getContentPane();//get the content pane to add components to
mainFrameContents.setLayout(null); //allowed setBounds on components to work properly
mainFrameContents.setBackground(Color.YELLOW);
myGame.makeComponents(); //makes all the sub components
//adds all subcomponents to content pane
mainFrameContents.add(greenButton);
mainFrameContents.add(blackButton);
mainFrameContents.add(newGameButton);
mainFrameContents.add(gamePanel);
myFrame.setVisible(true);
}
//gets the starting value of the tokens for the game
private void getStartingTokensValue()
{
myDialog = new JFrame("New Game Information");
myDialog.setSize(450, 150);
myDialog.setLocation(300, 100);
myDialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method
JLabel l = new JLabel("Please Enter the Number of Pieces for each side of the game (1-20)");
l.setBounds((myDialog.getSize().width - 420)/2, 0, 420, 30);
inputField = new JTextFieldNumber("0123456789");
inputField.setBounds((myDialog.getSize().width - 100)/2, 35, 100, 30);
inputButton = new JButton("Submit");
inputButton.setBounds((myDialog.getSize().width - 100)/2, 75, 100, 30);
inputButton.addActionListener(actionListen);
myDialog.setLayout(null);
myDialog.add(inputButton);
myDialog.add(l);
myDialog.add(inputField);
myDialog.setVisible(true);
}
private static class MyActionListen implements ActionListener
{
public void actionPerformed(ActionEvent ap)
{
if(ap.getSource().equals(greenButton)){
System.out.println("Requet to green move");
gamePanel.greenMove();
}else if(ap.getSource().equals(blackButton)){
System.out.println("Requet to black move");
}else if(ap.getSource().equals(newGameButton)){
System.out.println("Requet to start new game");
}else if(ap.getSource().equals(inputButton)){
if(inputField.getText().length()>0)
{
myGame.piecesPerSide = Integer.parseInt(inputField.getText());
if(inputField.checkAllCharacters() && (myGame.piecesPerSide <= 20) && (myGame.piecesPerSide>0))
{
myDialog.dispose();
myGame.makeGameFrame();
}else{
JOptionPane.showMessageDialog(inputField, "Please only type in an integer from 1 to 20");
}
}
}
}
}
}
DrawGamePieces.java
import java.awt.*;
import java.util.ArrayList;
import javax.swing.JPanel;
public class DrawGamePieces extends JPanel{
private ArrayList<GamePiece> gamePieces;
private int ballR = 15;
//paint or repaints the board
protected void paintComponent( Graphics g ){
super.paintComponent(g);
System.out.println("paint components called");
for(int i=0;i<gamePieces.size();i++)
{
GamePiece temp = gamePieces.get(i);
g.setColor(temp.getColor());
g.fillOval(temp.x,temp.y,ballR,ballR);
}
}
//init the game board
public DrawGamePieces(int piecesPerSide,int aWidth,int aHeight){
gamePieces = new ArrayList<GamePiece>();
super.setSize(aWidth, aHeight);
//space between wall and first piece
int blankSpace = (int)((aWidth - (ballR)*(2*piecesPerSide+1))/2);
//initalized the pieces in the arraylist
for(int i=0;i<(2*piecesPerSide+1);i++)
{
GamePiece temp = null;
if(i == 0) temp = new GamePiece(blankSpace,80,Color.GREEN);
if((i < piecesPerSide) && (i != 0)) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.GREEN);
if(i > piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.BLACK);
if(i == piecesPerSide) temp = new GamePiece(ballR+gamePieces.get(i-1).x,80,Color.YELLOW);
gamePieces.add(temp);
}
}
public void greenMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
repaint();
}
public void blackMove(){
GamePiece temp = gamePieces.get(5);
gamePieces.set(5, gamePieces.get(3));
gamePieces.set(3, temp);
}
private int pieceMoveable(Color c){
int index = -1, start = 0, end = 0,change = 0;
if(c == Color.GREEN){
start = 0;
end = gamePieces.size();
change = 1;
}else{
start = gamePieces.size();
end = 0;
change = -1;
}
for (int i=start;i<end;i= i+change){
//if(change = )
}
return index;
}
}
GamePiece.java
import java.awt.Color;
import java.awt.Point;
public class GamePiece extends Point{
private Color pieceColor;
public Color getColor(){
return pieceColor;
}
public GamePiece()
{
super();
}
public GamePiece(int x,int y,Color aColor)
{
super(x,y);
pieceColor = aColor;
}
}
Add more printfs to get more information about what is happening. Inside greenMove(), print out the contents of the ArrayList after you do the swap. Do the same inside paintComponent. In the printf, also indicate where these debugging messages are being printed from. In the loop in printComponent, print out the location and color of each piece as you draw it.