How to use the status bar in xamarin.forms shell? - xamarin.forms

I do not want to use full screen in android since there will be a bug.
I know how to do it in ios. please show me how to do it in android.

We could implement it by using Messaging Center .
in first page .cs
In your case it should be a shell
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<Object>(this,"Hide");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Send<Object>(this, "Show");
}
in Android project -> MainActivity
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
MessagingCenter.Subscribe<Object>(this, "Hide", (arg) => {
Window.AddFlags(WindowManagerFlags.TranslucentStatus);
Window.AddFlags(WindowManagerFlags.LayoutNoLimits);
});
MessagingCenter.Subscribe<Object>(this, "Show", (arg) => {
Window.ClearFlags(WindowManagerFlags.TranslucentStatus);
Window.ClearFlags(WindowManagerFlags.LayoutNoLimits);
});
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}

Related

phone volume key does not affect youtube volume (webview)

I set a webview and load youtube.
the problem is that when I play a video in youtube, my phone volume does not affect the volume of the video playing in youtube.
I have tried with setSreanVolume as you could see in the code snippet, to no avail.
Any suggestion and help will be appreciated
public class FragmentYoutube extends Fragment {
private WebView webView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_youtube, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.webview_youtube);
webView.setWebChromeClient(new MyChrome());
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.youtube.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (savedInstanceState==null){
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl("https://www.youtube.com");
}
});
}
AudioManager audioManager = (AudioManager) getActivity().getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.FLAG_SHOW_UI, AudioManager.FLAG_PLAY_SOUND);
webView.setOnKeyListener(new View.OnKeyListener() {
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
if (keyCode== KeyEvent.KEYCODE_BACK){
if (webView !=null){
if (webView.canGoBack()){
webView.goBack();
} else {
getActivity().onBackPressed();
}
return true;
}
}
}
return true;
}
});
}
}

Xamarin forms: System.NullReferenceException when using ZXing.Net.Mobile for scanning?

I am using the ZXing.Net.Mobile NuGet package for scanning barcode numbers. I have done everything as per this blog.
My Code
//Main Project Interface
public interface IQrScanningService
{
Task<string> ScanAsync();
}
//Android part implementation
[assembly: Dependency(typeof(XFBarcode.Droid.Services.QrScanningService))]
namespace projectname.Droid.Services
{
public class QrScanningService : IQrScanningService
{
public async Task<string> ScanAsync()
{
var optionsDefault = new MobileBarcodeScanningOptions();
var optionsCustom = new MobileBarcodeScanningOptions();
var scanner = new MobileBarcodeScanner()
{
TopText = "Scan the QR Code",
BottomText = "Please Wait",
};
var scanResult = await scanner.Scan(optionsCustom);
return scanResult.Text;
}
}
}
But when I execute I am getting System.NullReferenceException: 'Object reference not set to an instance of an object.'. What else I am missing here? I saw a similar thread here but don't how to download use a package from GitHub.
You missed the initialization step.
Try this:
public async Task<string> ScanAsync()
{
//Initialize the scanner first so it can track the current context
MobileBarcodeScanner.Initialize(MainActivity.Instance.Application);
var optionsDefault = new MobileBarcodeScanningOptions();
var optionsCustom = new MobileBarcodeScanningOptions();
var scanner = new MobileBarcodeScanner()
{
TopText = "Scan the QR Code",
BottomText = "Please Wait",
};
var scanResult = await scanner.Scan(optionsCustom);
return scanResult.Text;
}
in your MainActivity :
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
public static MainActivity Instance;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Instance = this;
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
You also could initialize in MainActivity OnCreate() method directly.
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
MobileBarcodeScanner.Initialize(Application); //initialize here
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}

OnOptionsItemSelected never trigger even though I use Android.Support.V7.Widget.Toolbar Xamarin Forms

In my Xamarin forms application, Android side I want to Override Navigation Bar back button click. I followed this tutorial but no luck. https://theconfuzedsourcecode.wordpress.com/2017/03/12/lets-override-navigation-bar-back-button-click-in-xamarin-forms/
Never triggering. But OnBackPressed() working well.
MainActivity.
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
//, ScreenStateListener
{
const int RequestLocationId = 0;
readonly string[] PermissionsGroupLocation =
{
//TODO add more permissions
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation,
Manifest.Permission.AccessLocationExtraCommands,
Manifest.Permission.AccessMockLocation,
Manifest.Permission.ReadExternalStorage,
Manifest.Permission.WriteExternalStorage,
Manifest.Permission.ReadPhoneState,
Manifest.Permission.Camera
};
// CustApp.ScreenListener.ScreenListener mScreenListener;
protected async override void OnCreate(Bundle savedInstanceState)
{
await TryToGetPermissions();
Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
Forms.SetFlags("CollectionView_Experimental"); //added for carousal view
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
Xamarin.FormsMaps.Init(this, savedInstanceState);
Xamarin.FormsGoogleMaps.Init(this, savedInstanceState);
UserDialogs.Init(this);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
CrossCurrentActivity.Current.Init(this, savedInstanceState);
Plugin.InputKit.Platforms.Droid.Config.Init(this, savedInstanceState);
LoadApplication(new App());
Android.Support.V7.Widget.Toolbar toolbar = this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
// coded to disappear status bar
Window.AddFlags(WindowManagerFlags.Fullscreen);
Window.ClearFlags(WindowManagerFlags.ForceNotFullscreen);
// mScreenListener = new CustApp.ScreenListener.ScreenListener(this);
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (item.ItemId == 16908332)
{
var currentpage =
Xamarin.Forms.Application.
Current.MainPage.Navigation.
NavigationStack.LastOrDefault() as HPayment;
if (currentpage?.CustomBackButtonAction != null)
{
// invoke the Custom back button action
currentpage?.CustomBackButtonAction.Invoke();
// and disable the default back button action
return false;
}
// if its not subscribed then go ahead
// with the default back button action
return base.OnOptionsItemSelected(item);
}
else
{
return base.OnOptionsItemSelected(item);
}
}
public override void OnBackPressed()
{
if (Rg.Plugins.Popup.Popup.SendBackPressed(base.OnBackPressed))
{
// Do something if there are some pages in the `PopupStack`
Task.Run(async () =>
{
popupPageClickInstance.Instance.popupPageSuccess = false;
AdvertisementInstance.Instance.AdvertisementIsSeen = false;
await PopupNavigation.Instance.PopAsync();
});
}
else
{
// Do something if there are not any pages in the `PopupStack`
}
}
}

Delete sharedpreferences on click button fragment

I wanted delete or reset value 0 once user click on reset button ,
here is code which i am using , but seem not be work ..
What wrong I am doing , i am not able to figure out , ..I also tried all way , using google to figure it out , but still stuck.
sharedPreferences = getActivity().getPreferences(1);
sharedPreferences.edit().remove("ccs11").commit();
sharedPreferences.edit().remove("spinner_paneer").commit();
Below is my fragment , on which i am trying to implement .
public PlanFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gain, container, false);
sharedPreferences = getActivity().getPreferences(1);
String cp1s11=sharedPreferences.getString("cp111", "0");
String cf1s11=sharedPreferences.getString("cf111", "0");
String ccs11=sharedPreferences.getString("cc111", "0");
//Button
btnfinish=(Button)rootView.findViewById(R.id.finish_gain);
btnfinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getActivity().getPreferences(1);
edt = sharedPreferences.edit();
edt.putString("ccs11", pro11.getText().toString());
edt.apply();
Intent intent = new Intent(getActivity(), MainActivity.class);
getActivity().startActivity(intent);
}
});
btnreset=(Button)rootView.findViewById(R.id.reset);
btnreset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getActivity().getPreferences(1);
sharedPreferences.edit().remove("ccs11").commit();
sharedPreferences.edit().remove("spinner_paneer").commit();
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}

Progress bar with thread

Now a days it's my first step in android. I am simply trying to implement progress bar with with a "Download" Button. When i press download button progress bar keep on progressing but when the whole progress gets over i am not able to hide progress bar. Here is my code. please help me.
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread timer = new Thread()
{
public void run()
{
try
{
for(int i=0; i<=50; i ++)
{
pb.incrementProgressBy(i);
sleep(1000);
}
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo.this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
};
timer.start();
}
});
}
}
You should only modifiy ui elements from the mainThread (the UI Thread) try
pb.post(new Runnable() {
#Override
public void run() {
pb.setVisibility(View.INVISIBLE);
}
})
instead.
Maybe u have to use the same thing for incrementing your progressbar. Alternativley you could use the AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html class. onProgressUpdate and onPostExecute are called in the UIThread automatically.
you can also use AsynTask that is a better solution...
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
new AsynTasks().execute();
}
});
}
class AsynTasks extends AsyncTask<Void, Integer, Void>
{
#Override
protected Void doInBackground(Void... params) {
for(int i=1;i<=100;i++)
{
SystemClock.sleep(1000);
publishProgress(i);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo .this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pb.setProgress(values[0]);
}
}
}
You should not do UI task from different thread.Use this...
public class ProgressBarDemo extends Activity
{
ProgressBar pb;
Button bt;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
bt = (Button) findViewById(R.id.button1);
pb.setVisibility(View.VISIBLE);
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread timer = new Thread()
{
public void run()
{
try
{
for(int i=1; i<=100; i ++)
{
pb.setProgress(i);
sleep(100);
}
}catch(Exception e){}
finally{
runOnUiThread( new Runnable() {
public void run() {
pb.setVisibility(View.INVISIBLE);
Toast.makeText(ProgressBarDemo .this, "Thank you for downloading", Toast.LENGTH_SHORT).show();
}
});
}
}
};
timer.start();
}
});
}
}

Resources