I made a simple program, which include TextView and Button; and every time the Button is clicked, the counter on TextView grows by 1.
I also wanted that every time I click the Button, toast message will be seen.
I opened a new item in Visual Studio to do it :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V7.App;
namespace perek1_helek1_dug1_listening
{
class Game_code : Button, Android.Views.View.IOnClickListener
{
private int point = 0;
private TextView screen;
public Game_code( TextView screen, Context context):base(context)
{
this.screen = screen;
}
public static void ShowToastMethod(Context context)
{
Toast.MakeText(context, "mymessage ", ToastLength.Long).Show();
}
public void OnClick(View v)
{
if (v.Id == Resource.Id.btnxml)
{
point++;
**ShowToastMethod( context);**
}
screen.Text = "" + point;
}
}
}
That is How MainActivity.cs looks like:
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
namespace perek1_helek1_dug1_listening
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
TextView tv;
Button btn;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
tv = (TextView)FindViewById(Resource.Id.textboxml);
btn = (Button)FindViewById(Resource.Id.btnxml);
Game_code game = new Game_code(tv, this);
btn.SetOnClickListener(game);
}
}
}
However, the line :
ShowToastMethod( context);
makes the error. What should I do?
I would suggest you use the events that C# has provided:
int point=0;
.
.
.
//after you find button view by ID
btn.Click+= delegate {
tv.Text=point++;
ShowToastMethod();
};
public void ShowToastMethod()
{
Toast.MakeText(this, "mymessage ", ToastLength.Long).Show();
}
I googled around and found that all I had to do is change the line :
ShowToastMethod( context);
to:
ShowToastMethod(this.Context );
Thank you anyway.
Related
I'm trying to retrieve the data inside of the generated key from firebase real time database using C# language and the retrieve data will show in RecyclerViewer. I try everything but still not showing in RecyclerView.
This is my code
how to solve this?
THIS IS THE LISTENER:
using AdamsonsEDApp.Data_Models;
using AdamsonsEDApp.Helpers;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Firebase.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static AdamsonsEDApp.Listeners.StaffListeners;
namespace AdamsonsEDApp.Listeners
{
public class PackageInfoListeners : Java.Lang.Object, IValueEventListener
{
List<PackageInfo> packageinfoList = new List<PackageInfo>();
public event EventHandler<PackageInfoDataEventArgs> PackageInfoRetrieved;
public class PackageInfoDataEventArgs : EventArgs
{
public List<PackageInfo> PackageInfo { get; set; }
}
public void OnCancelled(DatabaseError error)
{
throw new NotImplementedException();
}
public void OnDataChange(DataSnapshot snapshot)
{
if (snapshot.Value != null)
{
var child = snapshot.Children.ToEnumerable<DataSnapshot>();
packageinfoList.Clear();
foreach (DataSnapshot infoData in child)
{
PackageInfo info = new PackageInfo();
info.packageinfoID = infoData.Key;
info.packageinfoName = infoData.Child("infoName").Value.ToString();
info.packageinfoQty = infoData.Child("infoQty").Value.ToString();
packageinfoList.Add(info);
}
PackageInfoRetrieved.Invoke(this, new PackageInfoDataEventArgs { PackageInfo = packageinfoList });
}
}
public void Create()
{
DatabaseReference infoRef = AppDataHelper.GetDatabase().GetReference("packageinfo");
infoRef.AddValueEventListener(this);
}
}
}
This is the Activit
using AdamsonsEDApp.Adapters;
using AdamsonsEDApp.Data_Models;
using AdamsonsEDApp.Fragments;
using AdamsonsEDApp.Listeners;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AdamsonsEDApp.Resources.activities
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = false)]
public class eventpackageinfo_activity : AppCompatActivity
{
string packageinfoname, packageinfoqty;
TextView infonameText, infoqtyText;
ImageView /*removeButton,*/ backpackageButton/*, searchButton*/;
//EditText searchText;
RecyclerView packageinfoRecyclerView;
Button addinclusionsButton;
AddPackageInfoFragment addpackageinfoFragment;
PackageInfoAdapter packageinfoadapter;
List<PackageInfo> packageinfoList;
PackageInfoListeners infoListeners;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.eventpackageinfos);
infonameText = (TextView)FindViewById(Resource.Id.infonameText);
infoqtyText = (TextView)FindViewById(Resource.Id.infoqtyText);
addinclusionsButton = (Button)FindViewById(Resource.Id.addinclusionsButton);
backpackageButton = (ImageView)FindViewById(Resource.Id.backpackageButton);
packageinfoRecyclerView = (RecyclerView)FindViewById(Resource.Id.packageinfoRecyclerView);
backpackageButton.Click += BackpackageButton_Click;
addinclusionsButton.Click += AddinclusionsButton_Click;
RetrieveData();
}
private void AddinclusionsButton_Click(object sender, EventArgs e)
{
}
private void BackpackageButton_Click(object sender, EventArgs e)
{
Intent infointent = new Intent(this, typeof(eventpackage_activity));
StartActivity(infointent);
}
private void SetupPackageInfoRecyclerView()
{
packageinfoRecyclerView.SetLayoutManager(new Android.Support.V7.Widget.LinearLayoutManager(packageinfoRecyclerView.Context));
PackageInfoAdapter packageinfoadapter = new PackageInfoAdapter(packageinfoList);
packageinfoRecyclerView.SetAdapter(packageinfoadapter);
}
public void RetrieveData()
{
infoListeners = new PackageInfoListeners();
infoListeners.Create();
infoListeners.PackageInfoRetrieved += InfoListeners_PackageInfoRetrieved;
}
private void InfoListeners_PackageInfoRetrieved(object sender, PackageInfoListeners.PackageInfoDataEventArgs e)
{
packageinfoList = e.PackageInfo;
SetupPackageInfoRecyclerView();
}
}
}
Are you sure you're listening to the correct path in the database? Your code attaches a listener to:
DatabaseReference infoRef = AppDataHelper.GetDatabase().GetReference("packageinfo");
But your screenshot shows a node named eventpackage under the root.
Trying to change the color of the ScrollView bar. I found this link here but I would prefer to write a custom renderer as I have with all my other controls:
Color of ScrollBar in ScrollView
The problem is, I can't find any property/method that has any effect on the bar color. Here is my attempt so far:
public class CustomScrollRenderer : ScrollViewRenderer
{
public CustomScrollRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
this.ScrollBarSize = 50;
this.ScrollBarDefaultDelayBeforeFade = 60000;
this.SetBackgroundColor(Android.Graphics.Color.Red);
this.SetOutlineAmbientShadowColor(Android.Graphics.Color.Red);
this.SetOutlineSpotShadowColor(Android.Graphics.Color.Red);
}
}
In iOS , youneed to create a subclass of UIScrollView and rewrite the method LayoutSubviews
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIKit;
using App1;
using App1.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using ObjCRuntime;
[assembly:ExportRenderer(typeof(ScrollView),typeof(MyScrollViewRenderer))]
namespace App1.iOS
{
public class MyScrollViewRenderer: ViewRenderer<ScrollView, UIScrollView>
{
protected override void OnElementChanged(ElementChangedEventArgs<ScrollView> e)
{
base.OnElementChanged(e);
if(Control!=null)
{
SetNativeControl(new MyScrollView());
}
}
}
public class MyScrollView : UIScrollView
{
public override void LayoutSubviews()
{
foreach (UIView view in Subviews)
{
if (view.IsKindOfClass(new Class("UIImageView")))
{
view.BackgroundColor = UIColor.Red;
}
}
base.LayoutSubviews();
}
}
}
In Android
Create the scrollbar_style in Resource -> drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
android:angle="45"
android:centerColor="#color/blue"
android:endColor="#color/blue"
android:startColor="#color/blue" />
<corners android:radius="8dp" />
</shape>
using Android.App;
using Android.Content;
using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App1.Droid;
using Java.Lang.Reflect;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using static Android.Icu.Text.DateFormat;
using Field = Java.Lang.Reflect.Field;
[assembly: ExportRenderer(typeof(Xamarin.Forms.ScrollView), typeof(MyScrollViewRenderer))]
namespace App1.Droid
{
class MyScrollViewRenderer : ScrollViewRenderer
{
public MyScrollViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
Field mScrollCacheField = Java.Lang.Class.FromType(typeof(Android.Views.View)).GetDeclaredField("mScrollCache");
mScrollCacheField.Accessible = true;
Java.Lang.Object mScrollCache = mScrollCacheField.Get(this); // scr is your Scroll View
Field scrollBarField = mScrollCache.Class.GetDeclaredField("scrollBar");
scrollBarField.Accessible = true;
Java.Lang.Object scrollBar = scrollBarField.Get((Java.Lang.Object)mScrollCache);
Method method = scrollBar.Class.GetDeclaredMethod("setVerticalThumbDrawable", Java.Lang.Class.FromType(typeof(Drawable)));
method.Accessible = true;
// Set your drawable here.
method.Invoke(scrollBar, Resources.GetDrawable(Resource.Drawable.scrollbar_style));
}
}
}
MediationRewardedVideoAdListenerImplementor is not abstract and does not override abstract method zzc(Bundle) in MediationRewardedVideoAdListener
public class MediationRewardedVideoAdListenerImplementor SocialFeedTest.Android C:\Users\blain\source\repos\SocialFeedTest\SocialFeedTest\SocialFeedTest.Android\obj\Debug\90\android\src\mono\com\google\android\gms\ads\reward\mediation\MediationRewardedVideoAdListenerImplementor.java 4
following this tutorial here https://xamarinhelp.com/admob-xamarin-forms-display-google-ads-mobile-app/ . this is hard to diagnose for me because it doesn't break on a line number in my code it says the error is in auto generated code i do not understand. neither does it say there is a error in my code but it will not let me build it or emulate it.
heres my code
xamarin.forms
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace SocialFeedTest.Control
{
public class AdMobView : View
{
public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
nameof(AdUnitId),
typeof(string),
typeof(AdMobView),
string.Empty);
public string AdUnitId
{
get => (string)GetValue(AdUnitIdProperty);
set => SetValue(AdUnitIdProperty, value);
}
}
}
android
renderer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Gms.Ads;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SocialFeedTest.Control;
using SocialFeedTest.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
namespace SocialFeedTest.Droid
{
public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
{
public AdMobViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && Control == null)
SetNativeControl(CreateAdView());
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(AdView.AdUnitId))
Control.AdUnitId = Element.AdUnitId;
}
private AdView CreateAdView()
{
var adView = new AdView(Context)
{
AdSize = AdSize.SmartBanner,
AdUnitId = Element.AdUnitId
};
adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
adView.LoadAd(new AdRequest.Builder().Build());
return adView;
}
}
}
main activity
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace SocialFeedTest.Droid
{
[Activity(Label = "SocialFeedTest", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Android.Gms.Ads.MobileAds.Initialize(ApplicationContext, "ca-app-pub-5184019642309342~9928782520");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
ios
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Foundation;
using Google.MobileAds;
using SocialFeedTest.Control;
using SocialFeedTest.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
namespace SocialFeedTest.iOS
{
public class AdMobViewRenderer : ViewRenderer<AdMobView, BannerView>
{
protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(CreateBannerView());
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == nameof(BannerView.AdUnitId))
Control.AdUnitId = Element.AdUnitId;
}
private BannerView CreateBannerView()
{
var bannerView = new BannerView(AdSizeCons.SmartBannerPortrait)
{
AdUnitId = Element.AdUnitId,
RootViewController = GetVisibleViewController()
};
bannerView.LoadRequest(GetRequest());
Request GetRequest()
{
var request = Request.GetDefaultRequest();
return request;
}
return bannerView;
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
}
main
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace SocialFeedTest.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main(string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main(args, null, "AppDelegate");
}
}
}
If you are using that version there are going to be compile warnings because it is not updated for the SDK change in ads from google.
Your manifest now should have this.
meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-xxxxxxxxx-xxxxxxxxxx"
I suggest to use the Xamarin.GooglePlayServices.Ads.Lite if you only want ads.
You can see this link for how to do it.
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using System.Configuration;
namespace googlemaps
{
[Activity(Label = "googlemaps", MainLauncher = true, Icon = "#drawable/icon")]
MainActivity
public class MainActivity: Activity, IOnMapReadyCallback
{
private GoogleMap GMap;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.XMLFile1);
SetUpMap();
}
private void SetUpMap()
{
if (GMap == null)
{
MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map).GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap googleMap)
{
MarkerOptions MarkerOptions = new MarkerOptions();
MarkerOptions.SetPosition(new LatLng(16.03, 108));
MarkerOptions.SetTitle("My Postion");
googleMap.AddMarker(MarkerOptions);
googleMap.UiSettings.ZoomControlsEnabled = true;
googleMap.UiSettings.CompassEnabled = true;
googleMap.MoveCamera(CameraUpdateFactory.ZoomIn());
}
}
}
and
'Fragment' does not contain a definition for 'GetMapAsync' and no extension method 'GetMapAsync' accepting a first argument of type 'Fragment' could be found (are you missing a using directive or an assembly reference?) googlemaps
Thank you in advance
Your method "OnMapReady" needs to override the base class's method.
public override void OnMapReady(GoogleMap gmap)
{
//dostuff
}
I'm not 100% because I've never done this specifically, but I'm fairly certain it's complaining about this callback method.
I used this to find this out. This is the native Java for android development, but it mostly translates pretty well over into Xamarin from experience.
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Media;
namespace MoviePlayer
{
[Activity(Label = "MoviePlayer", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
MediaPlayer mp;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mp = new MediaPlayer();
mp.Prepare();
mp.SetDataSource()
mp.Start();
}
}
}
I don't know what should be in the mp.SetDataSource()
I looked on examples but didn't understand.
You need to pass a path to the file you want to play as a string to the SetDataSource() method to play that file.
Mono Documentation
Android Documentation