I got a method which evaluates whats in the string with what was set by user in TableView cells. (string have values like "343288709789" and each cell contains null or single digit number).
It works, however now I would like TableView to highlight(change background or text color) certain cells where user set wrong value. How can I achive this?
PS. Ive read similiar questions to this but I dont think I can achieve this in TableCell class implementation, because cells should change color only after uses press "Check" option.
private void compareAndEvaluate(String source, NewTableView newTableView){
ObservableList<MyData> data = newTableView.getData();
source = source.replaceAll("\\D+","");
System.out.println("data size: " +data.size() + "\n\n" + source);
int numOfValid = 0,
numOfInvalid = 0;
ObservableList<ObjectProperty<Integer>> rowData;
for(int i=0, n=0; i < data.size(); i++){ //rows(Y)
rowData = data.get(i).returnCellsData();
for(int j = 1; j < rowData.size(); ++j, ++n){ //columns(X)
Integer iNext = Integer.valueOf(String.valueOf(source.charAt(n)));
if( iNext == rowData.get(j).get() )
++numOfValid;
else
++numOfInvalid;
}
}
Dialogs.create().title("Results").masthead(null).message("Correct: " + numOfValid + ", Invalid: " + numOfInvalid).showInformation();
}
If that helps, here is implementation of TableCell used by TableView:
public class EditingCellNumbers extends TableCell<MyData, Integer>{
private TextField textField;
private TableView<MyData> parentTableView;
public EditingCellNumbers(TableView<MyData> parent) {
this.parentTableView = parent;
}
#Override
public void startEdit(){
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
textField.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
if(getItem() != null){
setText(String.valueOf(getItem()));
}else{
setText(null);
commitEdit(null);
}
setGraphic(null);
}
#Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
if(getTableColumn().getText() == "#"){
setStyle("-fx-font-weight: bold;"
+ "-fx-background-color: linear-gradient( from -100.0% 150.0% to 120.0% 100.0%, rgb(128,128,128) 0.0, rgb(255,255,255) 100.0);");
}else{
if(getItem() == null)
setStyle("-fx-border-color: lavender; -fx-border-width: 0 1 0 0;");
else
setStyle("-fx-border-color: palegreen; -fx-border-width: 0 1 1 0;");
}
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setStyle("-fx-background-color: ivory; -fx-border-color: red;");
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) -> {
if (!arg2) {
if(getItem() != null){
try{
commitEdit(Integer.valueOf(textField.getText()));
}catch(NumberFormatException f){
commitEdit(null);
}
}else
commitEdit(null);
}
});
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.BACK_SPACE){
if(getItem() != null){
numberOfEmptyCells.set(numberOfEmptyCells.get() + 1);
numberOfFilledCells.set(numberOfFilledCells.get() - 1);
}
commitEdit(null);
}else{
try{
int i = Integer.valueOf(textField.getText());
//digit given...
if( (i>=0) && (i<10) ){//making sure cell is filled with just one digit
if(getItem() == null){
numberOfEmptyCells.set(numberOfEmptyCells.get() - 1);
numberOfFilledCells.set(numberOfFilledCells.get() + 1);
}
commitEdit(Integer.valueOf(textField.getText()));
int selectedColumn = parentTableView.getSelectionModel().getSelectedCells().get(0).getColumn(); // gets the number of selected column
int selectedRow = parentTableView.getSelectionModel().getSelectedCells().get(0).getRow();
//moving to another cell editing
if(selectedColumn < numberOfColumns-1){
parentTableView.getSelectionModel().selectNext();
parentTableView.edit(selectedRow, parentTableView.getColumns().get(selectedColumn+1));
}else{
parentTableView.getSelectionModel().select(selectedRow+1, parentTableView.getColumns().get(1));
parentTableView.edit(selectedRow+1, parentTableView.getColumns().get(1));
}
}else
textField.clear();
}catch(NumberFormatException e){
textField.clear();
}
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
Instead of making your columns in your data model Integer, make them some kind of an object that stores both the integer and the evaluation result. Use the evaluation result to determine the colour of the cell in your customized TableCell.
Related
I have a Listview and Click Events in the respective listItems and need to get result back from the click events and populate on the List.
My BaseAdapter class is
public class RemnantListAdapter : BaseAdapter<InventorySlabs>
{
private PartialInventory context;
private List<InventorySlabs> RemnantList;
public RemnantListAdapter(PartialInventory partialInventory, List<InventorySlabs> remnantList)
{
this.context = partialInventory;
this.RemnantList = remnantList;
}
public override InventorySlabs this[int position]
{
get
{
return RemnantList[position];
}
}
public override int Count
{
get
{
return RemnantList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public override int ViewTypeCount
{
get
{
return Count;
}
}
public override int GetItemViewType(int position)
{
return position;
}
private class remnantHolder : Object
{
public Button EditRemnant1;
public TextView Remnant1 = null;
public TextView Rem_StockNMaterial1 = null;
public TextView Rem_Dimensions1 = null;
public TextView Rem_Status1 = null;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
remnantHolder holder = null;
if (convertView == null)
{
convertView = (convertView ?? context.LayoutInflater.Inflate(Resource.Layout.remnant_list, parent, false));
holder = new remnantHolder();
holder.EditRemnant1 = convertView.FindViewById<Button>(Resource.Id.editRemnant1);
holder.Remnant1 = convertView.FindViewById<TextView>(Resource.Id.remnant1);
holder.Rem_StockNMaterial1 = convertView.FindViewById<TextView>(Resource.Id.remnant_mtrl1);
holder.Rem_Dimensions1 = convertView.FindViewById<TextView>(Resource.Id.remnant_dimens1);
holder.Rem_Status1 = convertView.FindViewById<TextView>(Resource.Id.remnant_status1);
try
{
InventorySlabs remnantModel = this.RemnantList[position];
if (remnantModel != null)
{
holder.Remnant1.Text = "#" + remnantModel.ExtSlabNo;
holder.Rem_StockNMaterial1.Text = remnantModel.SellName + "-" + remnantModel.Depth + "-" + remnantModel.Finish;
double sqft = (remnantModel.Width * remnantModel.Height) / 144;
holder.Rem_Dimensions1.Text = "(" + remnantModel.Width.ToString() + " * " + remnantModel.Height.ToString() + ")" + sqft.ToString("N2");
holder.Rem_Status1.Text = remnantModel.Status;
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
context.StartActivityForResult(intent, 1);
}
};
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
convertView.Tag = holder;
}
else
{
holder = (remnantHolder)convertView.Tag;
}
return convertView;
}
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
if (remSlab != null)
{
remnantData.Width = double.Parse(data.GetStringExtra("remWidth"));
remnantData.Height = double.Parse(data.GetStringExtra("remHeight"));
double sqft = (remnantData.Width * remnantData.Height) / 144;
Rem_Dimensions.Text = "(" + remnantData.Width.ToString() + " * " + remnantData.Height.ToString() + ")" + sqft.ToString("N2");
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
}
}
In my Main Activity
I am calling the Result as
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
}
After editing the details in Edit view of the ListItem and close the Popup, I am not knowing how to Pass the Values to the Holder to Update in Listview.
You could pass the positon to the new activity in the click event and pass it back with the result intent.
For example:
holder.EditRemnant1.Click += delegate (object sender, System.EventArgs args)
{
if (remnantModel != null)
{
Intent intent = new Intent(context, typeof(EditRemnant));
intent.PutExtra("OpenPopType", 2);
intent.PutExtra("SlabNo", remnantModel.ExtSlabNo);
intent.PutExtra("Position", position );
context.StartActivityForResult(intent, 1);
}
};
And in the new activity:
protected override void OnCreate(Bundle savedInstanceState)
{
Intent intent = Intent;
var position =intent.GetIntExtra("Position", -1);
base.OnCreate(savedInstanceState);
Intent data = new Intent();
String text = "extSlabNo";
data.PutExtra("extSlabNo", text);
data.PutExtra("remWidth", 10);
data.PutExtra("remHeight", 20);
data.PutExtra("Position", position);
SetResult(Result.Ok, data);
}
Then you could modify the data in the adapter according to the positon value:
public void ActivityResult(int requestCode, Result resultCode, Intent data)
{
switch (requestCode)
{
case 1:
if (data != null)
{
try
{
string remSlab = data.GetStringExtra("extSlabNo");
int position = data.GetIntExtra("Position", -1);
if (remSlab != null && position >= 0)
{
RemnantList[position].Width = data.GetIntExtra("remWidth", -1);
RemnantList[position].Height = data.GetIntExtra("remHeight", -1);
NotifyDataSetChanged();
}
}
catch (Exception ex)
{
var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = method.Name;
var className = method.ReflectedType.Name;
MainActivity.SaveLogReport(className, methodName, ex);
}
}
break;
}
And reset the adapter in MainActivity OnActivityResult() method :
public class MainActivity : AppCompatActivity
{
RemnantListAdapter remnantListAdapter;
ListView listView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
List<InventorySlabs> remnantList = new List<InventorySlabs>();
for(var i = 0; i < 10; i++)
{
InventorySlabs inventorySlabs = new InventorySlabs();
inventorySlabs.Depth = i.ToString();
inventorySlabs.ExtSlabNo = i.ToString();
inventorySlabs.Finish = "Finish" + i.ToString();
inventorySlabs.Height = 200;
inventorySlabs.SellName = "SellName" + i.ToString();
inventorySlabs.Status = "Status" + i.ToString();
inventorySlabs.Width = 400;
remnantList.Add(inventorySlabs);
}
listView = FindViewById<ListView>(Resource.Id.listView1);
remnantListAdapter = new RemnantListAdapter(this, remnantList);
listView.Adapter = remnantListAdapter;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
remnantListAdapter.ActivityResult(requestCode, resultCode, data);
listView.Adapter = remnantListAdapter;
}
}
If an object is clicked, the next page should not be called immediately. But the click should remain on the object until you scroll through a wipe to the next page.
How can it hold the click command on an Item?
How can it swipe from the clicked Item to an other Page?
Update
Click one item > OnHold> swipe from the holded item to the left and right.
This is the actual behavior:
private int index = -1;
break;
}
return true;
}
}
To highlight the item when it is clicked, you can set background color to the item's view, to perform a swipe gesture for each item, I think you will need to implement IOnTouchListener for each item. Here I created an adapter to implement this feature:
public class LVAdapter : BaseAdapter<ListItemModel>, View.IOnTouchListener
{
private List<ListItemModel> items = new List<ListItemModel>();
private Activity context;
private int index = -1;
public enum SwipeAction
{
LR, // Left to Right
RL, // Right to Left
TB, // Top to bottom
BT, // Bottom to Top
None // when no action was detected
}
private int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
private SwipeAction maction = SwipeAction.None;
public LVAdapter(Activity context, List<ListItemModel> items) : base()
{
this.context = context;
this.items = items;
}
public override ListItemModel this[int position]
{
get { return items[position]; }
}
public override int Count
{
get { return items.Count; }
}
public override long GetItemId(int position)
{
return position;
}
private void SetSelectedItem(int position)
{
index = position;
NotifyDataSetChanged();
}
private class MyViewHolder : Java.Lang.Object
{
public TextView Name { get; set; }
public TextView Description { get; set; }
public int index { get; set; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
MyViewHolder holder = null;
var view = convertView;
if (view != null)
holder = view.Tag as MyViewHolder;
if (holder == null)
{
holder = new MyViewHolder();
view = context.LayoutInflater.Inflate(Resource.Layout.ItemCell, null);
holder.Name = view.FindViewById<TextView>(Resource.Id.nametxt);
holder.Description = view.FindViewById<TextView>(Resource.Id.detailtxt);
holder.index = position;
view.Tag = holder;
}
holder.Name.Text = items[position].Name;
holder.Description.Text = items[position].Description;
if (index != -1 && position == index)
{
holder.Name.SetBackgroundColor(Android.Graphics.Color.Red);
holder.Description.SetBackgroundColor(Android.Graphics.Color.Pink);
}
else
{
holder.Name.SetBackgroundColor(Android.Graphics.Color.RoyalBlue);
holder.Description.SetBackgroundColor(Android.Graphics.Color.SeaGreen);
}
view.SetOnTouchListener(this);
return view;
}
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
downX = e.GetX();
downY = e.GetY();
maction = SwipeAction.None;
break;
case MotionEventActions.Move:
upX = e.GetX();
upY = e.GetY();
var deltaX = downX - upX;
var deltaY = downY - upY;
if (Math.Abs(deltaX) > MIN_DISTANCE)
{
if (deltaX < 0)
{
maction = SwipeAction.LR;
}
else if (deltaX > 0)
{
maction = SwipeAction.RL;
}
return true;
}
else if (Math.Abs(deltaY) > MIN_DISTANCE)
{
if (deltaY < 0)
{
maction = SwipeAction.TB;
}
else if (deltaY > 0)
{
maction = SwipeAction.BT;
}
return false;
}
break;
case MotionEventActions.Up:
var holder = v.Tag as MyViewHolder;
if (maction == SwipeAction.None)
{
SetSelectedItem(holder.index);
}
else if (maction == SwipeAction.LR | maction == SwipeAction.RL)
{
if (holder.index == index)
context.StartActivity(typeof(Activity1));
}
break;
}
return true;
}
}
The ListItemModel is quite simple by my side:
public class ListItemModel
{
public string Name { get; set; }
public string Description { get; set; }
}
You can try to modify the model and holder as you need.
Hi everyone, i had to create custom info-window in xamarin forms as shown in the screenshot above. I have created a custom renderer for that but the problem i am having right now is that buttons are not getting clicked. Xamarin is taking entire info-window as a clickable view. Please guide me what i am doing wrong or is it possible to achieve button clicks in Xamarin forms. Thanks in advance.
Here is the code for custom renderer:
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
using SalesApp.Droid.CustomRenderer;
using Android.Widget;
using SalesApp.CustomControls;
using SalesApp.Droid.Listeners;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace SalesApp.Droid.CustomRenderer
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback
{
GoogleMap map;
List<CustomPin> customPins;
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins
Control.GetMapAsync(this);
}
}
public void OnMapReady(GoogleMap googleMap)
{
map = googleMap;
map.InfoWindowClick += OnInfoWindowClick;
map.SetInfoWindowAdapter(this);
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
map.Clear();
if (customPins != null)
{
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource((int)typeof(Resource.Drawable).GetField(pin.Image).GetValue(null)));
map.AddMarker(marker);
}
isDrawn = true;
}
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
//if (!string.IsNullOrWhiteSpace(customPin.Url))
//{
// var url = Android.Net.Uri.Parse(customPin.Url);
// var intent = new Intent(Intent.ActionView, url);
// intent.AddFlags(ActivityFlags.NewTask);
// Android.App.Application.Context.StartActivity(intent);
//}
Android.App.Application.Context.StartActivity(new Intent(Android.App.Application.Context, typeof(DialogActivity)));
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
map = googleMap;
map.SetInfoWindowAdapter(this);
map.InfoWindowClick += OnInfoWindowClick;
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var address = view.FindViewById<TextView>(Resource.Id.Address);
var contactPerson = view.FindViewById<TextView>(Resource.Id.ContactPerson);
var phone = view.FindViewById<TextView>(Resource.Id.Phone);
var zip = view.FindViewById<TextView>(Resource.Id.Zip);
var email = view.FindViewById<TextView>(Resource.Id.Email);
var cvr = view.FindViewById<TextView>(Resource.Id.CVR);
var turnover = view.FindViewById<TextView>(Resource.Id.Turnover);
var noOfEmp = view.FindViewById<TextView>(Resource.Id.NoOfEmp);
var leadStatus = view.FindViewById<TextView>(Resource.Id.LeadStatus);
var category = view.FindViewById<TextView>(Resource.Id.Cat);
if (infoTitle != null)
{
infoTitle.Text = customPin.LeedsAndCustomersData.FullName;
}
if (address != null)
{
address.Text = customPin.LeedsAndCustomersData.Address + " " + customPin.LeedsAndCustomersData.CityName;
}
if (contactPerson != null)
{
contactPerson.Text = customPin.LeedsAndCustomersData.FirstName;
}
if (phone != null)
{
phone.Text = customPin.LeedsAndCustomersData.Phone;
}
if (zip != null)
{
zip.Text = customPin.LeedsAndCustomersData.ZipCode;
}
if (email != null)
{
email.Text = customPin.LeedsAndCustomersData.Email;
}
if (cvr != null)
{
cvr.Text = customPin.LeedsAndCustomersData.CVR;
}
if (turnover != null)
{
turnover.Text = customPin.LeedsAndCustomersData.Turnover;
}
if (noOfEmp != null)
{
noOfEmp.Text = customPin.LeedsAndCustomersData.NoOfEmployees.ToString();
}
if (leadStatus != null)
{
leadStatus.Text = customPin.LeedsAndCustomersData.LeadStatus;
}
if (category != null)
{
category.Text = customPin.LeedsAndCustomersData.BusinessType;
}
//add listeners
OnTouchPhoneListener callButtonListener = new OnTouchPhoneListener();
phone.SetOnTouchListener(callButtonListener);
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
}
}
OnInfoWindowElemTouchListener:
using Android.OS;
using Android.Views;
using Android.Widget;
using System.Threading.Tasks;
using Android.Gms.Maps.Model;
using Android.Graphics.Drawables;
using Java.Lang;
namespace SalesApp.Droid.Listeners
{
public abstract class OnInfoWindowElemTouchListener : Java.Lang.Object, View.IOnTouchListener
{
private View view;
private Drawable bgDrawableNormal;
private Drawable bgDrawablePressed;
private Handler handler = new Handler();
private Marker marker;
private static bool endPressStatus = false;
private bool pressed = false;
//public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed)
//{
// this.view = this.view;
// this.bgDrawableNormal = this.bgDrawableNormal;
// this.bgDrawablePressed = this.bgDrawablePressed;
//}
public OnInfoWindowElemTouchListener(View view)
{
this.view = this.view;
}
public OnInfoWindowElemTouchListener(Button button)
{
}
public OnInfoWindowElemTouchListener()
{
}
public void setMarker(Marker marker)
{
this.marker = this.marker;
}
/*public bool OnTouch(View v, MotionEvent e)
{
if (e.Action == MotionEventActions.Down)
{
// do stuff
return true;
}
if (e.Action == MotionEventActions.Up)
{
// do other stuff
return true;
}
return false;
}*/
public bool OnTouch(View vv, MotionEvent e)
{
if (0 <= e.GetX() && e.GetX() <= vv.Width && 0 <= e.GetY() && e.GetY() <= vv.Height)
{
switch (e.ActionMasked)
{
case MotionEventActions.Down:
startPress();
break;
// We need to delay releasing of the view a little so it shows the
// pressed state on the screen
case MotionEventActions.Up:
//handler.PostDelayed(ConfirmClickRunnable, 150);
//Task.Factory.StartNew(() =>onClickConfirmed(view, marker));
Task.Factory.StartNew(() => onClickConfirmed());
Task.Delay(150);
break;
case MotionEventActions.Cancel:
endPress();
break;
default:
break;
}
}
else
{
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress()
{
if (!pressed)
{
pressed = true;
//handler.RemoveCallbacks(ConfirmClickRunnable);
if ((marker != null))
{
marker.ShowInfoWindow();
}
}
}
public bool endPress()
{
if (pressed)
{
this.pressed = false;
//handler.RemoveCallbacks(ConfirmClickRunnable);
view.SetBackgroundColor(Android.Graphics.Color.Green);
if ((marker != null))
{
marker.ShowInfoWindow();
}
endPressStatus = true;
return true;
}
else
{
endPressStatus = false;
return false;
}
}
//private Runnable confirmClickRunnable = new RunnableAnonymousInnerClassHelper(this);
private Runnable ConfirmClickRunnable = new Java.Lang.Runnable(() =>
{
if (endPressStatus)
{
//onClickConfirmed(view, marker);
}
});
/*private class RunnableAnonymousInnerClassHelper : Java.Lang.Object, Java.Lang.IRunnable
{
private readonly Context outerInstance;
public RunnableAnonymousInnerClassHelper(Context outerInstance)
{
this.outerInstance = outerInstance;
}
public void Run()
{
if (endPressStatus)
{
onClickConfirmed();
}
}
}*/
//public abstract void onClickConfirmed(View v, Marker marker);
public abstract void onClickConfirmed();
}
}
OnTouchPhoneListener:
using Android.Widget;
using System;
namespace SalesApp.Droid.Listeners
{
public class OnTouchPhoneListener : OnInfoWindowElemTouchListener
//public class OnTouchPhoneListener
{
Button button;
public OnTouchPhoneListener(Button button)
{
}
public OnTouchPhoneListener()
{
}
public override void onClickConfirmed() {
Console.WriteLine("call Button Clicked");
}
}
}
Why is the info window implemented in your custom renderer? This makes the class CustomMapRenderer do (at least) do two things, violate the SRP and makes the code way harder to understand.
Instead I'd go with the custom renderer just for the map. Then in Xamarin.Forms you can implement the overlay with Xamarin.Forms means (e.g. the map view in an absolute or relative layout and the overlay in the same layout but a reduced size). Please see the following pseudo-XAML
<ContentPage [...]>
<AbsoluteLayout>
<local:MapView x:Name="MapView" AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0,0,1,1" />
<local:MapOverlay AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".5, .5, .5, .5" />
</AbsoluteLayout>
</ContentPage>
Then you can introduce a viewmodel PinInfoViewModel which is exposed by MapView.SelectedPinInfo and can be set as MapOverlay.BindingContext
<local:MapOverlay AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".5, .5, .5, .5" BindingContext="{Binding Source={x:Reference MapView}, Path=SelectedPinInfo}" />
MapOverlay - in turn - binds to all the properties of PinInfoViewModel. Last thing we'll have to do is making the overlay invisible if no pin is selected. For this purpose we expose MapView.IsPinSelected and bind MapOverlay.IsVisible to it
<local:MapOverlay AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds=".5, .5, .5, .5" BindingContext="{Binding Source={x:Reference MapView}, Path=SelectedPinInfo}" IsVisible="{Binding Source=MapView, Path=IsPinSelected}" />
While up to this point we have not done anything to solve your issue, you can now implement the overlay way simpler, e.g. with a StackLayout. And you can bind the Buttons commands to do whatever you'd like to do.
I am using web service for showing image in imageview. But web service image show in SYSTEM.BYTE[] Format. So how to Convert or display the image in imageview in xamarin android application??
Webservice.asmx:
[WebMethod(MessageName = "BindHospName", Description = "Bind Hospital Name Control")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
[System.Xml.Serialization.XmlInclude(typeof(GetHospName))]
public string BindHosp(decimal SpecID)
{
JavaScriptSerializer objJss = new JavaScriptSerializer();
List<GetHospName> HospName = new List<GetHospName>();
try
{
ConnectionString();
cmd = new SqlCommand("select b.HID,b.HospName,b.Logo from HospitalRegBasic b inner join HospitalRegClinical c on b.HID=c.HID " +
"where b.EmailActivationCode <> '' and b.EmailActivationStatus = 1 and b.Status = 1 and c.SPEC_ID = #SpecID ", conn);
cmd.Parameters.AddWithValue("#SpecID", SpecID);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
var getHosp = new GetHospName
{
HospID = dr["HID"].ToString(),
HospName = dr["HospName"].ToString(),
HospLogo = dr["Logo"].ToString()
};
HospName.Add(getHosp);
}
}
dr.Close();
cmd.Dispose();
conn.Close();
}
catch (Exception)
{
throw;
}
return objJss.Serialize(HospName);
}
Class.cs:
namespace HSAPP
{
class ContListViewHospNameClass : BaseAdapter<GetHospNames>
{
List<GetHospNames> objList;
Activity objActivity;
public ContListViewHospNameClass (Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
this.objList = objMyList;
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public override long GetItemId(int position)
{
return position;
}
public static Bitmap bytesToBitmap(byte[] imageBytes)
{
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
return bitmap;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
byte[] img =item.HospLogo;
Bitmap bitmap = BitmapFactory.DecodeByteArray(img, 0, img.Length);
convertView.FindViewById<ImageView>(Resource.Id.imgLogo).SetImageBitmap(bitmap);
return convertView;
}
}
}
This is JSON Code:
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
try
{
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString(),JArrayValue[count]["Logo"]);
list.Add(getHospName);
count++;
}
listView.Adapter = new ContListViewHospNameClass(this, list);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
public static void SetImageFromByteArray (byte[] iArray, UIImageView imageView)
{
if (iArray != null && iArray.Length > 0) {
Bitmap bitmap = BitmapFactory.DecodeByteArray (iArray, 0, iArray.Length);
imageView.SetImageBitmap (bitmap);
}
}
That's it. If this is not working, your byte array may not be a valid image.
public static bool IsValidImage(byte[] bytes)
{
try {
using(MemoryStream ms = new MemoryStream(bytes))
Image.FromStream(ms);
}
catch (ArgumentException) {
return false;
}
return true;
}
I have run into a few problems when trying to get the camera to work accordingly... The camera Demo Works on the 8520 device (Has a memory Card) but does not work on the 9780 device (Has No Memory Card) the error given
ERROR Class java.lang.ArrayOutOfBoundsException :index 0>=0
My code Sample:
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
}else if( root.equalsIgnoreCase("store/") ) {
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
// PATH = System.getProperty("file:///store/home/user/pictures/")+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
System.out.println("----------1");
fileconn=(FileConnection)Connector.open(PATH);
System.out.println("----------2");
if(fileconn.exists()){
fileconn.delete();
System.out.println("----------3");
}
fileconn.create();
System.out.println("----------4");
OutputStream os=fileconn.openOutputStream();
System.out.println("----------5");
os.write(rawImage);
GetfileName =fileconn.getName();
System.out.println("----------6");
System.out.println("GetfileName----------"+GetfileName);
fileconn.close();
System.out.println("----------7");
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
System.out.println("----------8");
if(_p!=null)
_p.close();
System.out.println("----------9");
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
System.out.println("Debug------------10");
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
System.out.println("Debug------------11");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
System.out.println("Debug------------12");
_videoControl.setVisible(true);
_p.start();
System.out.println("Debug------------13");
if(videoField != null){
add(videoField);
System.out.println("Debug------------14");
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
on the 8520 (Has a Memory Card) the code works fine on the 9780 (Has no Memory Card) the the code stops at "System.out.println("debug---1")", can anyone please tell me if you can see any problem with my code???
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
This is the sollution, My "SD card availability" code only returned true which caused the picture not to save when the blackberry had no memory card inserted. # Eugen Martynov Please read through the code and you will see it is there :)