I am trying to do a simple toggle silent mode app. I got the for dummies book and no luck so far.
What I want to do is when the audio is on I want to change my text on my button to Turn off (using a string). and when pressed I want it to change to another string. But I can't get this thing down right. I have tried several ways so far. Any suggestions ?
package com.example.silentmodetoggle;
import android.os.Bundle;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TSMMainActivity extends Activity {
//Instantiate an AudioManager to manage the ringer state
private AudioManager mAudioManager;
private boolean mPhoneIsSilent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tsmmain);
mAudioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
checkIfPhoneIsSilent();
setButtonClickListener();
//does this even work?
TextView textView=(TextView)findViewById(R.string.silence_phone);
}//onCreate
private void setButtonClickListener()
{
Button toggleButton = (Button) findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (mPhoneIsSilent)
{ //set to normal mode
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mPhoneIsSilent = false;
}
else
{
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_SILENT);
mPhoneIsSilent = true;
}
//now toggle the UI again
toggleUi();
}
});
}
private void checkIfPhoneIsSilent()
{
int ringerMode = mAudioManager.getRingerMode();
if (ringerMode == AudioManager.RINGER_MODE_SILENT)
{
mPhoneIsSilent = true;
}
else
{
mPhoneIsSilent = false;
}
}
private void toggleUi()
{
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
Drawable newPhoneImage;
if (mPhoneIsSilent)
{
//i think i should put it here.
newPhoneImage = getResources().getDrawable(R.drawable.phone_silent);
}
else
{
newPhoneImage = getResources().getDrawable(R.drawable.phone_on);
}
imageView.setImageDrawable(newPhoneImage);
}
private void textView(int silencePhone) {
// TODO Auto-generated method stub
}
#Override
protected void onResume()
{
super.onResume();
checkIfPhoneIsSilent();
toggleUi();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tsmmain, menu);
return true;
}
}
Try this:
#Override
public void onClick(View v)
{
if (mPhoneIsSilent)
{ //set to normal mode
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
mPhoneIsSilent = false;
((Button)v).setText("Turn On");
}
else
{
mAudioManager
.setRingerMode(AudioManager.RINGER_MODE_SILENT);
mPhoneIsSilent = true;
((Button)v).setText("Turn Off");
}
Hope this helps :)
In the OnClickListener(View v) the argument v is the button you clicked on. Therefore you can call the method setText(String s) and change the text.
It should be explicitly cast to its type as v is a generic type of View.
Related
I have tried to look out for an answer to the behavior of my views but I seem not find any question or solution related to it. My recycler views seemed to be set up well. I just realized that my app is not responding in the right way to the OnClickListeners.
I have set up toasts in my adapter for the recycler view click events. When i have 10 views. When i click on a view, it gives a text of another view. It seems it randomly gives me the text of another view amongst the 9 remaining views. What could be the cause of this?
Activity
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
FrameLayout content = (FrameLayout)FindViewById(Resource.Id.content_frame);
LayoutInflater.Inflate(Resource.Layout.Main, content);
setUpRecyclerView();
}
public void setUpRecyclerView(){
rv = FindViewById<RecyclerView>(Resource.Id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.Orientation = LinearLayoutManager.Vertical;
layoutManager.ReverseLayout = true;
layoutManager.StackFromEnd = true;
rv.HasFixedSize = true;
rv.SetLayoutManager(layoutManager);
}
Adapter
public class FeedViewHolder : RecyclerView.ViewHolder, View.IOnClickListener, View.IOnLongClickListener
{
public FeedViewHolder(View itemView):base(itemView)
{
//binding of variables here
itemView.SetOnClickListener(this);
itemView.SetOnLongClickListener(this);
}
public void OnClick(View v)
{
itemClickListener.OnClick(v, AdapterPosition, false);
}
public bool OnLongClick(View v)
{
itemClickListener.OnClick(v, AdapterPosition, true);
return true;
}
public class FeedAdapter : RecyclerView.Adapter, ItemClickListener
{
public FeedAdapter(RssObject rssObject, Context mContext)
{
this.mContext = mContext;
this.inflater = LayoutInflater.From(mContext);
activity = (MainActivity)mContext;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
hold = holder as FeedViewHolder;
//binding
hold.itemClickListener = this;
}
public void OnClick(View view, int position, bool isLongClick)
{
Toast.MakeText(activity, "Main text : " + hold.txtContent.Text, ToastLength.Long).Show();
}
public override int ItemCount
{
get { return rssObject.items.Count; }
}
}
}
}
I'm doing a multiple choice quiz game, and im tryinng to highlight the correct answer in green if the wrong answer is clicked. for example if i have A , B , C and D and "A" is the correct answer. i want if i choose "B" to turn B to red color and display the correct answer to green which is in this case "A". Right now i have if i click the right answer it displays green, as i want it. and if i press wrong answer it displays red. what im missing is when i click wrong answer i want to also highlight the correct answer.
Here's my functions:
In the Game controller:
public bool theAnswerIsCorrect;
public bool IsCorrected()
{
return theAnswerIsCorrect;
}
public void AnswerButtonClick(bool isCorrect)
{
if (isCorrect)
{
Debug.Log("I'm Correct");
theAnswerIsCorrect = true;
playerScore += currentRoundData.pointAddedForCorrectAnswer;
scoreDisplayText.text = "Score: " + playerScore.ToString();
}
else
theAnswerIsCorrect = false;
// Do we still have questions?
if (questionPool.Length > questionIndex + 1)
{
//questionIndex++;
UpdateQuestionIndex();
StartCoroutine(DelayTime(3));
// ShowQuestion();
}
else
{
EndRound();
}
}
And this is an a class that just holdes my data
public class answerData {
public string answerTxt;
public bool isCorrect;
}
This is being used in the ButtonClick function (the code in the begging of the question) -> this line
gameController.AnswerButtonClick (AnswerData.isCorrect);
And in the inspector i specify by the bool what is the correct answer
*** NEW SCRIPT HERE "Picking up the Correct button"
// store reference to btn text
public Text answerText;
private answerData AnswerData;
private GameController gameController;
public static AnswerButton _instace;
private void Awake()
{
_instace = this;
}
// Use this for initialization
void Start ()
{
gameController = FindObjectOfType<GameController> ();
}
public void Setup(answerData data)
{
AnswerData = data;
answerText.text = AnswerData.answerTxt;
}
IEnumerator ReturnButtonColor()
{
yield return new WaitForSeconds(2.9f);
GetComponent<Button>().image.color = Color.white;
Debug.Log("HiB");
}
public void HandleClick()
{
gameController.AnswerButtonClick (AnswerData.isCorrect);
if (gameController.IsCorrected())
{
GetComponent<Button>().image.color = Color.green;
Debug.Log("im true");
StartCoroutine(ReturnButtonColor());
}
else
{
GetComponent<Button>().image.color = Color.red;
// gameController.IsCorrected().image.color = Color.green;
StartCoroutine(ReturnButtonColor());
}
}
Thank you
I am assuming that all option button have same script attached.
Create one delegate and register this in your script which is attached to your option button.
Like this
Create delegate and event
#region DELEGATES
public delegate void OnQuestionOptionClicked ();
public static event OnQuestionOptionClicked onQuestionOptionClicked;
#endregion
#region DELEGATE_CALLS
private void RaiseOnQuestionOptionClicked ()
{
if (onQuestionOptionClicked != null)
onQuestionOptionClicked ();
}
#endregion
Register it
void OnEnable ()
{
onQuestionOptionClicked += OnQuestionOptionClicked;
}
void OnDisable ()
{
onQuestionOptionClicked -= OnQuestionOptionClicked;
}
#region DELEGATE_EVENT_LISTENER
void OnQuestionOptionClicked ()
{
GetComponent<Button>().interactable = false;
if (AnswerData.isCorrect){
GetComponent<Button>().image.color = Color.green;
Debug.Log("im true");
}
}
#endregion
Your setup method
public void Setup(answerData data)
{
AnswerData = data;
answerText.text = AnswerData.answerTxt;
GetComponent<Button>().interactable = true;
GetComponent<Button>().image.color = Color.white;
}
And on button click event
#region BUTTON_CLICK_LISTENER
public void ButtonClick()
{
gameController.AnswerButtonClick (AnswerData.isCorrect);
if (!gameController.IsCorrected())
{
GetComponent<Button>().image.color = Color.red;
Debug.Log("im true");
// StartCoroutine(ReturnButtonColor());
}
RaiseOnQuestionOptionClicked ();
}
#endregion
Hope this solution helps you.;)
Like using GetComponent<Button>().image.color = Color.green; in the if statement , you could simply add in /*Button A*/.image.color = Color.green; in the else statement.
What #BadWolf in the comments is saying is the correct answer. If you need more coding help you have to include more information. How do you determine the Correct Button? Does it have a special name in the Scene? Does the gameController know which button is the correct? It seems gameController knows which Button is the correct one so you should create a method which will look something like:
public Button GetCorrectButton(){
return theCorrectButton;
}
I don't know the code for how you see if it is the correct button but I'm guessing you have some way where you use the Correct Button. Find the Correct Button and return it in the method GetCorrectButton.
which you will then use in your code like:
public void ButtonClick()
{
gameController.AnswerButtonClick (AnswerData.isCorrect);
if (gameController.IsCorrected())
{
GetComponent<Button>().image.color = Color.green;
Debug.Log("im true");
// StartCoroutine(ReturnButtonColor());
}
else
{
GetComponent<Button>().image.color = Color.red;
// Like this:
gameController.GetCorrectButton().image.color = Color.green;
}
}
I can be more specific if I get some more information/code to see!
I have my fragments inside view page but I would like to reload the data on the tab selected.I tried returning PositionNone in the GetItemPosition method in my FragmentPagerAdapter but it does not work.
I tried adding notifyDataSetChanged(); on tab selected but it throws nullpointer exception.
I even tried setting the viewPager.setOffscreenPageLimit
I managed to find the link :
Replace Fragment inside a ViewPager
but it is on java.
I have managed to convert most of the code to c# but gets stuck on the commented code. I am not sure how to call the listener and instantiate the class at the same time? There is a lot of similar question but unfortunately not one in Xamarin Android.
I need to do this in xamarin android. Any help will be greatly appreciated.
This is my FragmentAdapter
public class TabsFragmentPagerAdapter : FragmentPagerAdapter
{
private readonly Android.Support.V4.App.Fragment[] fragments;
static readonly int NUM_ITEMS = 2;
private readonly Android.Support.V4.App.FragmentManager FragmentManager;
private Android.Support.V4.App.Fragment mFragmentAtPos0;
private readonly ICharSequence[] titles;
public TabsFragmentPagerAdapter(Android.Support.V4.App.FragmentManager fm, Android.Support.V4.App.Fragment[] fragments, ICharSequence[] titles) : base(fm)
{
this.fragments = fragments;
this.titles = titles;
}
public override int Count
{
get
{
return fragments.Length;
}
}
public override int GetItemPosition(Java.Lang.Object objectValue)
{
if (objectValue.GetType() == typeof(startJobFrag) && mFragmentAtPos0.GetType() == typeof(jobCaptureFrag))
{
return PositionNone;
}
return PositionUnchanged;
}
public override ICharSequence GetPageTitleFormatted(int position)
{
return titles[position];
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
if (position == 0)
{
if (mFragmentAtPos0 == null)
{
//not working
}
return mFragmentAtPos0;
}
else
{
return new jobCaptureFrag();
}
}
This is my Actvity
void FnInitTabLayout()
{
var fragments = new Android.Support.V4.App.Fragment[]
{
new frag 1(),
new frag 2(),
new frag 3(),
};
//Tab title array
var titles = CharSequence.ArrayFromStringArray(new[] {
"Page 1",
"Page 2",
"Page 3",
});
var viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
//viewpager holding fragment array and tab title text
//viewPager.
viewPager.Adapter = new TabsFragmentPagerAdapter(SupportFragmentManager, fragments, titles);
// Give the TabLayout the ViewPager
tabLayout.SetupWithViewPager(viewPager);
viewPager.PageSelected += (object sender, ViewPager.PageSelectedEventArgs e) =>
{
//FnInitTabLayout();
if(e.Position == 0)
{
//handle tab click/selected
}
};
}
public interface FirstPageFragmentListener
{
void onSwitchToNextFragment();
}
Fragment
public class Fragment1: Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
View view = inflater.Inflate(Resource.Layout.myview, container, false);
}
}
I managed to solve it on my own.
In My activity I called NotifyDataSetChanged() on Pageselected event
Activity
ViewPager.PageSelected += (object sender, ViewPager.PageSelectedEventArgs e) =>
{
if (e.Position == 1)
{
_pager.Adapter.NotifyDataSetChanged();
}
};
Then I changed my Adapter from FragmentPagerAdapter to FragmentStatePagerAdapter and override the GetItemPosition.
Adapter
public class TabsFragmentPagerAdapter : FragmentStatePagerAdapter
{
public override int GetItemPosition(Java.Lang.Object objectValue)
{
return PositionNone;
}
}
Refresh a specific tab - inside the Adapter
public override Android.Support.V4.App.Fragment GetItem(int position)
{
if(position == 1) //second tab selected
{
NotifyDataSetChanged();
}
return fragments[position];
}
I'm sure there's a better way to do it but this works.
Hello Guys i'm working on a app that when you click a button it opens the stock iOS camera and lets you take a picture I know how to do this in objc but the apps written in C# using Xamarin i've looked on the Xamarin forms and google for help but everything is post iOS 8 witch this app needs to run so here's the code that I have so far:
photobutton.TouchUpInside += delegate {
//insert Xamarin code here
};
EDIT I ADDED THE Following code to a new class:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace ToolBelt.iOS
{
public partial class cameraViewController : UIViewController
{
public cameraViewController (IntPtr handle) : base (handle)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
//UIPopoverController popover = new UIPopoverController (ctrl);
// Perform any additional setup after loading the view, typically from a nib.
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
UIImagePickerController picker = new UIImagePickerController ();picker.PrefersStatusBarHidden ();
picker.SourceType = UIImagePickerControllerSourceType.Camera;
PresentViewController(picker, true, () => {});
}
}
}
Any Help would be awesome
Thank you in advance!
You've almost finished it. Just add Delegate handler for Picker, take a look on this: https://developer.xamarin.com/recipes/ios/media/video_and_photos/choose_a_photo_from_the_gallery/
I added events below follow your existing source code
UIImagePickerController imagePicker;
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
imagePicker = new UIImagePickerController();
imagePicker.PrefersStatusBarHidden ();
imagePicker.SourceType = UIImagePickerControllerSourceType.Camera;
//Add event handlers when user finished Capturing image or Cancel
imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia;
imagePicker.Canceled += Handle_Canceled;
//present
PresentViewController(picker, true, () => {});
}
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
// determine what was selected, video or image
bool isImage = false;
switch(e.Info[UIImagePickerController.MediaType].ToString()) {
case "public.image":
Console.WriteLine("Image selected");
isImage = true;
break;
case "public.video":
Console.WriteLine("Video selected");
break;
}
// get common info (shared between images and video)
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:"+referenceURL.ToString ());
// if it was an image, get the other image info
if(isImage) {
// get the original image
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if(originalImage != null) {
// do something with the image
Console.WriteLine ("got the original image");
imageView.Image = originalImage; // display
}
} else { // if it's a video
// get video url
NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl;
if(mediaURL != null) {
Console.WriteLine(mediaURL.ToString());
}
}
// dismiss the picker
imagePicker.DismissModalViewControllerAnimated (true);
}
void Handle_Canceled (object sender, EventArgs e) {
imagePicker.DismissModalViewControllerAnimated(true);
}
Im running good with this:
public partial class CameraViewController : UIViewController
{
static UIImagePickerController picker;
static UIImageView staticImageView;
public CameraViewController() : base("CameraViewController", null)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
base.Title = "Kamera";
staticImageView = this.imageView;
}
partial void openCamera(UIButton sender)
{
if (UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
{
picker = new UIImagePickerController();
picker.Delegate = new CameraDelegate();
picker.SourceType = UIImagePickerControllerSourceType.Camera;
NavigationController.PresentViewController(picker, true, null);
}
else
{
this.button.Hidden = true;
}
}
class CameraDelegate : UIImagePickerControllerDelegate
{
public override void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info)
{
picker.DismissModalViewController(true);
var image = info.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
CameraViewController.staticImageView.Image = image;
}
}
}
The method "openCamera" is connected to the Button Event via .xib file.
You can use XLabs: https://github.com/XLabs/Xamarin-Forms-Labs
XLabs provides the Camera service which can take a picture: https://github.com/XLabs/Xamarin-Forms-Labs/wiki/Camera
If you are not familiar with XLabs, these are a few links which help you getting started. Please remember to add the XLabs nuget package to all of your projects (PCL, iOS, Android)
http://www.codenutz.com/getting-started-xamarin-forms-labs-xaml-mvvm-ioc/
https://github.com/XLabs/Xamarin-Forms-Labs/tree/master/Samples
How to use Resolver in XLabs: https://forums.xamarin.com/discussion/20178/xamarin-forms-labs-peeps
EDIT: XLabs MediaPicker can be used in both Xamarin.Forms and non-Xamarin.Forms app.
In my democode an embeded windows media player starts to load and play a video. The player shows no controls, all other options are the default options. So far this works.
What does not work is that not all userinteraction is stopped. For instance it is possible to change the mode to fullscreen with a doubleclick and it also is possible to get a full context with a right click.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
axWindowsMediaPlayer1.uiMode = "none";
}
private void button1_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = #"C:\stackoverflow.mp4";
}
}
How can i isolate the player from the user and only control the player via code?
A friend just helped me to solve this.
Disabling the context menĂ¼ was rather easy
axWindowsMediaPlayer1.enableContextMenu = false;
Disabling the doubleclick requires a message filter - there is already a solution on the web.
Application.AddMessageFilter((IMessageFilter)CustomFilter(this/*Form*/, axWMP));
I have rewritten my example and i am now using this code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
axWindowsMediaPlayer1.uiMode = "none";
axWindowsMediaPlayer1.enableContextMenu = false;
Application.AddMessageFilter(new IgnoreMouseClickMessageFilter(this, axWindowsMediaPlayer1));
}
private void button1_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = #"C:\stackoverflow.mp4";
}
}
class IgnoreMouseClickMessageFilter : IMessageFilter
{
private Control parent { get; set; }
private Control target { get; set; }
public IgnoreMouseClickMessageFilter(Control parent, Control target)
{
this.parent = parent;
this.target = target;
}
public bool PreFilterMessage(ref Message messageBeforeFiltering)
{
const Boolean FilterTheMessageOut = true;
const Boolean LetTheMessageThrough = false;
if (IsNull(parent)) return LetTheMessageThrough;
if (IsNull(target)) return LetTheMessageThrough;
if (WasNotClickedOnTarget(parent, target)) return LetTheMessageThrough;
if (MessageContainsAnyMousebutton(messageBeforeFiltering)) return FilterTheMessageOut;
return LetTheMessageThrough;
}
private bool MessageContainsAnyMousebutton(Message message)
{
if (message.Msg == 0x202) return true; /* WM_LBUTTONUP*/
if (message.Msg == 0x203) return true; /* WM_LBUTTONDBLCLK*/
if (message.Msg == 0x204) return true; /* WM_RBUTTONDOWN */
if (message.Msg == 0x205) return true; /* WM_RBUTTONUP */
return false;
}
private bool WasNotClickedOnTarget(Control parent, Control target)
{
Control clickedOn = parent.GetChildAtPoint(Cursor.Position);
if (IsNull(clickedOn)) return true;
if (AreEqual(clickedOn, target)) return false;
return true;
}
private bool AreEqual(Control controlA, Control controlB)
{
if (controlA == controlB) return true;
return false;
}
private bool IsNull(Control control)
{
if (control == null) return true;
return false;
}
}
Special thanks to my unnamed friend and to "remarkpk11" from the Microsoft Developer Network Frorums.
There are some smaller issues with the code - i dont like that the Messages are hidden from me in the first place and i also would love to get rid of the two global dependencies Cursor and Application. But as far as this question goes i consider it answered.
try axWindowsMediaPlayer1.Ctlenabled = False
EDIT: sorry, this is for vb..
axWindowsMediaPlayer1.Ctlcontrols.stop();