I Want to display a listview when i click a button in Monodroid. i tried this coding. its not running. Can anyone correct this - xamarin.android

I want to display a listview when I click a button in Monodroid. I tried the following code, however it doesn't run. Can anyone correct this?
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button> (Resource.Id.btn);
button1.Click += delegate { listviewFunction(); };
}
public void listviewFunction()
{
ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item, _countries);
ListView.TextFilterEnabled = true;
ListView.ItemClick += (sender, args) => Toast.MakeText(Application, ((TextView) args.View).Text, ToastLength.Short).Show();
}

Try just:
button1.Click += ...

Declare a ListView globally:
private ListView _listView;
Now (1)create the ListView, OR (2)get it from a axml file:
(1)
_listView = new ListView(this);
(2)
_listView = (ListView)View.FindViewById(Resource.Id.MyList);
Now create your adapter, then:
_listView.SetAdapter(myAdapter);
Then create your ItemClick handler:
_listView.ItemClick += (sender, args) => Toast.MakeText(Application, ((TextView) args.View).Text, ToastLength.Short).Show();

Related

How to add radio button to radio group in Xamarin for Android via code behind?

The title already describes what I want to do: I'm working with Xamarin for Android. Now I'd like to have a RadioGroup and fill it with RadioButtons via code behind and not via XAML. How can I do this? I don't find any setter...
Why do I need this? My small Android app has a Load button which loads entries from a web service. Each entry should be represented by a RadioButton so that the user has a flexible selection.
Here's an example I put together for you that creates the Radio Group and Radio Buttons dynamically along with how to determine which button is selected by the user at run-time.
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
var layout = new LinearLayout(this) {
Orientation = Orientation.Vertical
};
// Create Radio Group
var rg = new RadioGroup(this);
layout.AddView(rg);
// Add Radio Buttons to Radio Group
for (int i = 1; i < 6; i++) {
var rb = new RadioButton(this) { Text = $"Radio Button {i}" };
rg.AddView(rb);
}
// Show Radio Button Selected
lblOutput = new TextView(this);
layout.AddView(lblOutput);
rg.CheckedChange += (s, e) => {
lblOutput.Text = $"Radio Button {e.CheckedId} Selected";
};
SetContentView(layout);
}
Output
As an alternative, I've implemented a solution using a ListView:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
Speakers = new List<ISpeaker>();
FindViewById<Button>(Resource.Id.loadButton).Click += LoadButtonOnClick;
}
private async void LoadButtonOnClick(object sender, EventArgs e)
{
Speakers = await LoadSpeakersAsync();
var sourceListView = FindViewById<ListView>(Resource.Id.sourceListView);
sourceListView.Adapter = new ArrayAdapter<ISpeaker>(this, Android.Resource.Layout.SimpleListItem1, Speakers);
}

Can I bind the return to a condition?

I have the following problem:
My method opens a JDialog with a bunch of buttons (only one in example code). I want to click a button and thereby choose an ImageIcon for my method to return. But the Method does not wait for me to click a button. It opens the window and then returns an empty ImageIcon.
public class Kartenauswahl {
ImageIcon bandit;
public ImageIcon auswahlfenster() {
int bwidth = new Integer(150);
int bheight = new Integer(225);
bandit = new ImageIcon("cover/Bandit.jpe");
bandit.setImage(bandit.getImage().getScaledInstance(bwidth,bheight,Image.SCALE_DEFAULT));
final JDialog kartenwahl = new JDialog();
kartenwahl.setTitle("Kartenwahl");
kartenwahl.setSize(1500,1000);
kartenwahl.setVisible(true);
kartenwahl.setLayout(new FlowLayout());
ImageIcon returnicon= new ImageIcon();
final JButton b1 = new JButton(); //just to get the Icon out of the void loop
JButton B1 = new JButton(bandit); //this is going to be the button I want to click to choose the ImageIcon which is returned
B1.setContentAreaFilled(false);
B1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
b1.setIcon(bandit);
kartenwahl.dispose();
}
});
kartenwahl.add(B1);
returnicon = (ImageIcon) b1.getIcon();
return returnicon;
}
}
Question: can I bind the return statement to a condition? Like "only return after I clicked that Button B1"?
Hi sorry for the long wait. I have written an custom JDialog that should work for you.
public class CustomDialog extends JDialog {
JButton[] buttons;
ImageIcon selectedImageIcon;
public CustomDialog() {
setSize(500, 500);
setLayout(new GridLayout(4, 6));
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
selectedImageIcon = ((ImageIcon) ((JButton) e.getSource()).getIcon());
dispose();
}
};
buttons = new JButton[24];
for(int i = 0; i < 24; i++) {
buttons[i] = new JButton(new ImageIcon("path_to_your_image_file"));
buttons[i].addActionListener(actionListener);
add(buttons[i]);
}
setVisible(true);
}
public ImageIcon getSelectedImageIcon() {
return selectedImageIcon;
}
}
The initial size is not that important the GridLayout is. you mentioned that you would need 24 buttons so I created an grid with 4 rows and 6 columns.
Then I create the buttons in a loop and adding the same Listener to set the selection icon with the icon of the pressed button. Afterwards I dispose the screen triggering an windowClosed event.
You could simply create this Dialog from your main class and wait for the response like so:
public class main {
public static void main(String[] args) {
CustomDialog customDialog = new CustomDialog();
customDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
ImageIcon icon = customDialog.getSelectedImageIcon();
//do something with your icon
}
});
}
}
Don't forget to mark this answer as correct if it fixes your problem.
Have a good one!

Capture Tab Click Event in Mono

I have a Tabhost in my app with 3 tabs. The tabs are all working fine.
Now I want to perform some additional logic when the tab is selected?.
For Example: In one of my tabs, I provide an option for the user to sort things in different order and update the another tab.
how can we get the click event of TabHost?
I have updated the Tab Creation (Activity) part.
Thanks in Advance.
[Activity(Label = "My Activity")]
public class TabSearch : TabActivity
{
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Search_WOTab);
/* ******************** Adding 2 Tab Controls and setting Activity classes to Tabs added ******************** */
TabHost.TabSpec tspec;
Intent intent;
intent = new Intent(this, typeof(WOSearch));
intent.AddFlags(ActivityFlags.NewTask);
tspec = TabHost.NewTabSpec("Search");
tspec.SetIndicator("Search", Resources.GetDrawable(Resource.Drawable.Search));
tspec.SetContent(intent);
TabHost.AddTab(tspec);
intent = new Intent(this, typeof(WOFilter));
intent.AddFlags(ActivityFlags.NewTask);
tspec = TabHost.NewTabSpec("Filter");
tspec.SetIndicator("Filter", Resources.GetDrawable(Resource.Drawable.Filter));
tspec.SetContent(intent);
TabHost.AddTab(tspec);
TabHost.TabChanged += (sender, e) =>
{
Toast.MakeText(this, TabHost.CurrentTab.ToString(), ToastLength.Short).Show();
};
}
catch (Exception ex)
{
Toast.MakeText(this, ex.InnerException.ToString(), ToastLength.Short);
}
}
You can use the TabHost.TabChanged event.
tabHost.TabChanged += (sender, e) => {
if (tabHost.CurrentTab == 0) {
// Do what you want.
}
};
PS: Xamarin Docs is your friend.
Edit:
You should modify your code to this...
//TabHost.TabChanged += TabHost_TabChanged;
TabHost.TabChanged += (sender, e) =>
{
Toast.MakeText(this, TabHost.CurrentTab.ToString(), ToastLength.Short).Show();
};
TabHost.CurrentTab is the index of the selected tab.

Why Data Can not Pass to Second Activity

Using XamarinStudio and below code base on the Sample in the tutorial. Here the questions.
Do I need to generate the AndroidManifest from the Project Option> Android Application when testing the App ?
Why there is no data passing over even I have generated an AndroidManifest , the code :
---Activity 1
[Activity (Label = "HelloMultiScreen", MainLauncher = true,Icon = "#drawable/icon")]
public class FirstActivity : Activity
{
int count = 1;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
//Use UI created in Main.axml
SetContentView (Resource.Layout.Main);
var showSecond = FindViewById (Resource.Id.showSecond);
showSecond.Click += (sender, e) => {
var second = new Intent(this, typeof(SecondActivity));
second.PutExtra("FirstData", "Data from FirstActivity");
StartActivity (typeof(SecondActivity));
};
}
}
---Activity 2
[Activity (Label = "SecondActivity")]
public class SecondActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create your application here
SetContentView (Resource.Layout.Second);
var label = FindViewById (Resource.Id.screen2Label);
label.Text = Intent.GetStringExtra("FirstData") ?? "Data not available";
}
}
Thanks
Ok I found the problem when I remade the project myself.
The problem lies in this piece of code:
var second = new Intent(this, typeof(SecondActivity));
second.PutExtra("FirstData", "Data from FirstActivity");
StartActivity (typeof(SecondActivity));
What happens is that you make an Intent with the right data. But you start a new activity without that data.
To fix it change the code to this:
var second = new Intent(this, typeof(SecondActivity));
second.PutExtra("FirstData", "Data from FirstActivity");
StartActivity(second);`

Lightswitch printing an html file - System.UnauthorizedAccessException: Invalid cross-thread access

I make a new button in Lightswitch and put this code inside to print only a single file:
partial void StampaDeposito_Execute()
{
PrintDocument printInvoice = new PrintDocument();
printInvoice.PrintPage +=
new EventHandler<PrintPageEventArgs>(printInvoice_PrintPage);
printInvoice.Print("TemplateEmail.htm");
}
void printInvoice_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.HasMorePages = false;
}
but when I click the button following error appears: System.UnauthorizedAccessException: Invalid cross-thread access.
Is there a workaround to solve this?
Try this:
using Microsoft.LightSwitch.Threading
partial void StampaDeposito_Execute()
{
Dispatchers.Main.BeginInvoke(() => {
PrintDocument printInvoice = new PrintDocument();
printInvoice.PrintPage +=
new EventHandler<PrintPageEventArgs>(printInvoice_PrintPage);
printInvoice.Print("TemplateEmail.htm");
});
}
void printInvoice_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.HasMorePages = false;
}
When you get an error about thread access, more often than not you can fix it by invoking the code on the main dispatcher.

Resources