I need to compare the image loaded as background into my imageView. I do so like this:
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
switch (v.getId()) {
case R.id.hero1:
if(v.getBackground() == R.drawable.hero1){
//do something
}
break;
case R.id.hero2:
//other stuff
}
But v.getBackground() does not compare to what I have in drawable folder.
Why?
Note that v.getBackgroundResource() is not available.
You can do like this-
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
switch (v.getId()) {
case R.id.hero1:
if (v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.hero1).getConstantState())) {
// Do something here
}
break;
case R.id.hero2:
//other stuff
}
Related
Trying to work on small use case where i have to add string of websites in a queue. if the site repeats then i have to update the numberofVisits+1. Else i would add that object into the queue. Something wrong with updateCount code. Please let me know
here is the code snippet. I am unable to move forward on this.
public CLassName(String url, int numVisits) {
this.url = url;
this.numVisits = numVisits;
}
public int getNumVisits() {
return this.numVisits;
}
public String getUrl() {
return this.url;
}
public void setNumVisits(int updatedNumVisits) {
this.numVisits = updatedNumVisits;
}
private static Queue<ClassName> sites = new LinkedList<ClassName>();
// Method to find the website in the queue and increment the visited count by 1, adding new node in case website is not found
public static void update(String url) {
//code should go in here. // THis is wrong code
if (sites.isEmpty()) sites.add(new ClassName(url,1));
while(!sites.isEmpty()) {
String tmpUrl = sites.peek().getUrl();
int numVisits = sites.peek().getNumVisits();
if(tmpUrl!=null && tmpUrl.equalsIgnoreCase(url)) {
sites.add(new ClassName(tmpUrl,numVisits+1));
} else if(tmpUrl!=null){
sites.add(new ClassName(tmpUrl,numVisits));
} else {
sites.add(new ClassName(url,1));
}
}
}
public static void main(String[] args) {
String[] visitedSites = { "www.google.co.in", "www.google.co.in", "www.facebook.com", "www.upgrad.com", "www.google.co.in", "www.youtube.com",
"www.facebook.com", "www.facebook.com", "www.google.co.in", "www.microsoft.com", "www.9gag.com", "www.netflix.com",
"www.netflix.com", "www.9gag.com", "www.microsoft.com", "www.amazon.com", "www.amazon.com", "www.uber.com", "www.amazon.com",
"www.microsoft.com" };
for (String url : visitedSites) {
update(url);
}
Thanks for the recommendation. I did a small tweek to address the problem.
I did not add Dummy site
Added a counter and incremented so that it is always < the size of queue
Here is my solution and it works
public static void update(Queue<String> sites,String url,int numberOfVisits)
{
if ( sites.isEmpty()) sites.add(url); // first time
boolean flag = false;
int counter = 0
while (!sites.empty && counter<sites.size()) //go over all the urls in the queue
{
if (sites.head().equalsIgnoreCase(url))
{
flag = true;
break;
}
sites.insert(sites.remove()); //removing the head and inserting it to the end of the queue
counter ++;
}
if (!flag==true) {
numberOfVisits=numberOfVisits+1;
}
else {
sites.insert(url);
}
}
the update method just could be like this;
boolean increased = false;
Iterator<ClassName> statIterator = sites.iterator();
while (statIterator.hasNext()) {
ClassName st = statIterator.next();
if (st.getUrl().equals(url)) {
st.setNumVisits(st.getNumVisits()+1);
increased = true;
break;
}
}
if (!increased) {
sites.add(new ClassName(url,1));
}
In a Xamarin.Forms and Xamarin.Android project I create a Custom Render and Adapter for a ListView.
The adapter implements BaseAdapter and ISectionIndexer. The custom render of this control is using FastScroll feature, in Android when you tap this scroll a bubble with a index letter appears. This works fine, but my idea is to have a way to catch the selected index after releasing scroll and that scroll "bubble" disappears.
I thought with the following class (in the GetSectionForPosition method) could achieve that:
public class ListViewconIndexAdapter : BaseAdapter<string>, ISectionIndexer
{
string[] items;
Activity context;
string[] sections;
Java.Lang.Object[] sectionsObjects;
Dictionary<string, int> alphaIndex;
public ListViewconIndexAdapter(Activity context, string[] items) : base()
{
this.context = context;
this.items = items;
alphaIndex = new Dictionary<string, int>();
for (int i = 0; i < items.Length; i++)
{
var key = items[i][0].ToString();
if (!alphaIndex.ContainsKey(key))
alphaIndex.Add(key, i);
}
sections = new string[alphaIndex.Keys.Count];
alphaIndex.Keys.CopyTo(sections, 0);
sectionsObjects = new Java.Lang.Object[sections.Length];
for (int i = 0; i < sections.Length; i++)
{
sectionsObjects[i] = new Java.Lang.String(sections[i]);
}
}
public override Java.Lang.Object GetItem(int position)
{
return position;
}
public override long GetItemId(int position)
{
return position;
}
public override string this[int position]
{
get { return items[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null)
view = context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItem1, null);
view.FindViewById<TextView>(Android.Resource.Id.Text1).Text = items[position];
return view;
}
//Fill in cound here, currently 0
public override int Count
{
get { return items.Length; }
}
// -- ISectionIndexer --
public int GetPositionForSection(int section)
{
return alphaIndex[sections[section]];
}
public int GetSectionForPosition(int position)
{ // this method isn't called in this example, but code is provided for completeness
int prevSection = 0;
for (int i = 0; i < sections.Length; i++)
{
if (GetPositionForSection(i) > position)
{
break;
}
prevSection = i;
}
Console.WriteLine(prevSection);
Console.WriteLine(sections[prevSection]);
//Toast.MakeText(context, sections[prevSection], ToastLength.Short).Show();
Xamarin.Forms.MessagingCenter.Send<object,string>(this, "CambioSeccion", sections[prevSection]);
return prevSection;
}
}
I put those Console.writeline for checking the index letter and that Message send is a way to send it back to PCL/NET Standard code (to show an DisplayAlert or something).
But the problem is that method firing is not consistent, for example, sometimes you fast scroll down to 'C' but Console doesn't print anything after releasing it there, but after touching it again where you leave it, it fires up. But sometimes it works like i want, it prints after release the scroll at selected index.
ListView has two different scroll listeners, AbsListView.IOnScrollListener and AbsListView.IOnScrollChangeListener (this one was added in API 23) and a touch listener (AbsListView.IOnTouchListener)
I think based upon your use-case, you are looking for the OnScrollStateChanged and when it goes into idle state and you are not touching the listview, do something (or vice versa).
Example (adjust to your needs of course):
public class MyScrollListener : Java.Lang.Object, AbsListView.IOnTouchListener, AbsListView.IOnScrollListener, AbsListView.IOnScrollChangeListener //(API23)
{
bool touching;
bool scrolling;
public void OnScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
}
public void OnScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY)
{
}
public void OnScrollStateChanged(AbsListView view, [GeneratedEnum] ScrollState scrollState)
{
switch(scrollState)
{
case ScrollState.Idle:
if (!touching)
{
scrolling = false;
GetSelection();
}
break;
default:
scrolling = true;
break;
}
}
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Up:
touching = false;
if (!scrolling)
GetSelection();
break;
default:
touching = true;
break;
}
return true;
}
void GetSelection()
{
// touch and srolling is done, do something
}
}
Usage:
var scrollListener = new MyScrollListener();
listView.SetOnTouchListener(scrollListener);
listView.SetOnScrollListener(scrollListener);
listView.SetOnScrollChangeListener(scrollListener); // API23
I have a TableView named tableVerre and I want to have every row of it checked for a criteria ( stock column value ) and execute some code on them as I scroll so I wrote this code but it makes the program consume a lot of CPU time, I'm not familiar with Lambda expressions so is there a simpler way to write this ? :
tableVerre.addEventFilter(ScrollEvent.ANY, new EventHandler<ScrollEvent>() {
#Override
public void handle(ScrollEvent scrollEvent) {
stock.setCellFactory(column -> {
return new TableCell<VerreFX, Number>() {
#Override
protected void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
TableRow<VerreFX> currentRow = getTableRow();
if (empty || item == null) {
setText("");
setGraphic(null);
currentRow.setStyle(tableVerre.getStyle());
} else {
setText(getItem().toString());
}
if (!isEmpty()) {
if ((int) item == 0 && st.getVerresBOX()) currentRow.setStyle("-fx-background-color:lightcoral");
}
}
};
});
}
});
The table view will reuse cells as the user scrolls, and will automatically call updateItem on the cells when they are reused for new items. So you should set the cell factory only once, and then just let the table view take care of doing the job it is designed to do. You can set the cell factory in the initialize() method if you are using FXML, or just wherever you create the table and columns otherwise.
Your cell implementation isn't quite correct: because a cell may be reused to display any two different items arbitrarily, you need to account for all possible conditions. In your implementation, if a cell shows an item for which item.intValue()==0 and is then reused to show an item for which item.intValue() != 0, then the style will not be updated correctly.
Also note that you should "convert" a Number to an int by calling intValue().
TableColumn<VerreFX, Number> stock ;
// ...
stock.setCellFactory(column -> new TableCell<VerreFX, Number>() {
#Override
protected void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
TableRow<VerreFX> currentRow = getTableRow();
if (empty || item == null) {
setText("");
setGraphic(null);
currentRow.setStyle(tableVerre.getStyle());
} else {
setText(getItem().toString());
}
if (!isEmpty()) {
if (item.intValue() == 0 && st.getVerresBOX()) {
currentRow.setStyle("-fx-background-color:lightcoral");
} else {
currentRow.setStyle(tableVerre.getStyle());
}
}
}
});
You should be able to remove the scroll event handler entirely.
Firstly beside over CPU time using you didn't cover all the scrolling situations because if the user scrolls using the key Down/Up or using the scroll bar the scroll event will not be fired. So you have to add two more EventFilter, the first will handle the Scrolling using the Scrollbar.
tableVerre.addEventFilter(MouseEvent.MOUSE_CLICKED,(
MouseEvent event)->
{
if ((event.getTarget() instanceof TableColumnHeader) | event.isDragDetect()) {
System.err.println("Mouse Draged : " + event.toString());
stock.setCellFactory((TableColumn<VerreFX, Number> column) -> {
return new TableCell<VerreFX, Number>() {
#Override
protected void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
TableRow<VerreFX> currentRow = getTableRow();
if (empty || item == null) {
setText("");
setGraphic(null);
currentRow.setStyle(tableVerre.getStyle());
} else {
setText(getItem().toString());
}
if (!isEmpty()) {
if ((int) item == 0 && st.getVerresBOX()) {
currentRow.setStyle("-fx-background-color:lightcoral");
}
}
}
};
});
}
});
And the second one will handle the scrolling using the keyboard Key DOWN/UP.
tableVerre.addEventFilter(KeyEvent.KEY_PRESSED,new EventHandler<KeyEvent>(){
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.DOWN | event.getCode() == KeyCode.UP) {
stock.setCellFactory(column -> {
return new TableCell<VerreFX, Number>() {
#Override
protected void updateItem(Number item, boolean empty) {
super.updateItem(item, empty);
TableRow<VerreFX> currentRow = getTableRow();
if (empty || item == null) {
setText("");
setGraphic(null);
currentRow.setStyle(tableVerre.getStyle());
} else {
setText(getItem().toString());
}
if (!isEmpty()) {
if ((int) item == 0 && st.getVerresBOX()) {
currentRow.setStyle("-fx-background-color:lightcoral");
}
}
}
};
});
}
System.err.println("Key Pressed : " + event.toString());
}
});
I want to log the information of user's action, such as button click, show composite. So I use event listener. When I use SWT.FocusIn, I can get the real composite name, but when I use SWT.Show I can't get the real class name.
Listener listener = new Listener() {
public void handleEvent(Event event) {
switch (event.type) {
case SWT.FocusIn: {
if(event!=null&&event.widget!=null){
Control parent = ((Control)event.widget).getParent();
while(parent!=null&&(parent.toString().startsWith("Composite")
||parent.toString().startsWith("Group")
||parent.toString().startsWith("Splitter")
)){
parent = parent.getParent();
}
if(parent!=null){
**//This place I can get "SWT.FocusIn:DoSomethingComposite"(The subclass of Composite).**
log.info("SWT.FocusIn:" + parent.toString());
}
}
break;
}
case SWT.Show: {
if (event.widget != null) {
if(event.widget instanceof Composite) {
Composite composite = (Composite)(event.widget);
**//But this place I just get "SWT.Show:Composite".**
log.info("SWT.Show:" + event.widget.toString());
}
}
break;
}
default: {
break;
}
}
}
}
PlatformUI.getWorkbench().getDisplay().addFilter(SWT.Show, listener);
PlatformUI.getWorkbench().getDisplay().addFilter(SWT.FocusIn, listener);
I have a search text-box in my app. In my database there are two column named English and Bangla. I can search either Bangla or English. there is a button beside search text-box.By default English search is activated. I can change the search option by clicking the button. It works correctly but problem is that the search is very slow.
search option selection code by clicking button is:
private void button5_Click(object sender, RoutedEventArgs e)
{
if (SearchMood % 2 != 0)
{
//search bangla column from the database
button5.Content = "Eng";
}
else {
//search english column from the database
button5.Content = "Bng";
}
SearchMood++;
}
Code for searching is:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
List<dataLists> mylist = new List<dataLists>();
string word = textBox1.Text;
try
{
if (SearchMood % 2 == 0)// for english search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.English.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
else // for bangla search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.Bangla.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
}
catch { }
}
How can I increase the performance of searching??? Can anyone give any solution|???
N:B: My table creation script looks like
public System.Data.Linq.Table<Dic> Dics
{
get
{
return this.GetTable<Dic>();
}
}
public System.Data.Linq.Table<Learn_table> Learn_tables
{
get
{
return this.GetTable<Learn_table>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dic")]
public partial class Dic : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Serial;
private string _English;
private string _Bangla;
private System.Nullable<int> _Fav;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnSerialChanging(int value);
partial void OnSerialChanged();
partial void OnEnglishChanging(string value);
partial void OnEnglishChanged();
partial void OnBanglaChanging(string value);
partial void OnBanglaChanged();
partial void OnFavChanging(System.Nullable<int> value);
partial void OnFavChanged();
#endregion
public Dic()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="serial", Storage="_Serial", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Serial
{
get
{
return this._Serial;
}
set
{
if ((this._Serial != value))
{
this.OnSerialChanging(value);
this.SendPropertyChanging();
this._Serial = value;
this.SendPropertyChanged("Serial");
this.OnSerialChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="english", Storage="_English", DbType="NVarChar(2000)")]
public string English
{
get
{
return this._English;
}
set
{
if ((this._English != value))
{
this.OnEnglishChanging(value);
this.SendPropertyChanging();
this._English = value;
this.SendPropertyChanged("English");
this.OnEnglishChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="bangla", Storage="_Bangla", DbType="NVarChar(2000)")]
public string Bangla
{
get
{
return this._Bangla;
}
set
{
if ((this._Bangla != value))
{
this.OnBanglaChanging(value);
this.SendPropertyChanging();
this._Bangla = value;
this.SendPropertyChanged("Bangla");
this.OnBanglaChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="fav", Storage="_Fav", DbType="Int")]
public System.Nullable<int> Fav
{
get
{
return this._Fav;
}
set
{
if ((this._Fav != value))
{
this.OnFavChanging(value);
this.SendPropertyChanging();
this._Fav = value;
this.SendPropertyChanged("Fav");
this.OnFavChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Your problem appears in using TextChanged event Handler. Place a breakpoint there and you will see it firing twice and hence causing the slow performance for you. It seems a bug in WP7 TextBox control.
Use KeyUp event handler, instead of textBox1_TextChanged
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
//your code
}
Hope this solves your problem. !!
You can use of AutoCompleteBox rather than use of TextBox. AutoCompleteBox available in Microsoft.Phone.Control.Toolkit.
Execute you select query at once when you select language on buttonClick and assign result of your query to AutoCompleteBox.Itemsource. It should really increase search performance.
<toolkit:AutoCompleteBox x:Name="AutoBoxFood" Width="440" SelectionChanged="txtFodd_SelectionChanged" FilterMode="StartsWith" HorizontalAlignment="Left" Height="70"/>
Add indexes to the columns in the database file.