While working with Titanium application, came across a situation where I want to change image of Spinner (i.e. Picker in Titanium)
Taking Picker's object I'm able to create spinner and manipulate data but not finding any mechanism which change the default image of spinner
Thinking to do like this replace-picker-with-button
any other idea?
You can directly change image of the spinner by its backgroundImage property.
For Example
backgroundImage: '/images/dropdown.png.
It will only work for Android and did not work with iPhone.
So if you want to make same UI for both Ios and Android then you can follow below trick.
Here is the global method which you can use to create and display Picker.
/*
pickerData: is the array of the values which you want to display in the picker
funName: is the callback function which will be called when user will select the row from picker. this function will have two parameters first will be selected row's text and second is the index of the selected row
title: is the title of the picker
index: is the default selected index in the picker
*/
function showPicker(pickerData, funName, title, index) {
if (title == undefined || title == "") {
title = "";
}
if (pickerData == undefined || pickerData == null) {
pickerData = [];
}
index = index || 0;
if (pickerData.length <= index || index < 0) {
index = 0;
}
var selectedCategory = pickerData[0];
var win = Ti.UI.createWindow({
backgroundColor : 'transparent',
});
//Check weather the Os is IOs or Android
//globals.isIos is the parameter which is indicating that current OS is IOs or not?
if (globals.isIos) {
var picker = Ti.UI.createPicker({
selectionIndicator : true,
bottom : 0,
width : '100%',
isSpinner : true,
});
data = [];
for (var p = 0; p < pickerData.length; p++) {
data.push(Ti.UI.createPickerRow({
title : pickerData[p],
index : p
}));
}
picker.add(data);
Ti.API.info("Tab Index" + index);
picker.setSelectedRow(0, index, true);
var selectedIndex = 0;
picker.addEventListener('change', function(e) {
selectedCategory = e.row.title;
selectedIndex = e.row.index;
});
//toolbar
var done = Titanium.UI.createButton({
title : 'Done',
style : Titanium.UI.iPhone.SystemButtonStyle.DONE,
});
done.addEventListener('click', function(e) {
funName(selectedCategory, selectedIndex);
win.close();
});
var title = Titanium.UI.createLabel({
text : title,
textAlign : 'left',
color : 'white',
font : {
fontWeight : 'bold',
fontSize : globals.isIpad ? 18 : "14dp"
}
});
var flexSpace = Titanium.UI.createButton({
systemButton : Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});
var toolbar = Titanium.UI.iOS.createToolbar({
items : [title, flexSpace, done],
bottom : 216,
borderTop : true,
borderBottom : false,
barColor : '#3F3F3F'
});
win.addEventListener('click', function(e) {
win.close();
});
win.add(picker);
win.add(toolbar);
win.open();
} else {
var pickerView = Titanium.UI.createOptionDialog({
selectedIndex : index
});
pickerView.title = title;
data = [];
for (var p = 0; p < pickerData.length; p++) {
data.push(pickerData[p]);
};
pickerView.options = data;
pickerView.addEventListener('click', function(e) {
selectedCategory = pickerData[e.index >= 0 ? e.index : index];
funName(selectedCategory, e.index >= 0 ? e.index : index);
});
pickerView.show();
}
return win;
}
Now create one button or lable inside your window and set the dropdown image to its background.
So it will look like dropdown now handle click of the button and put below code in it.
var data = ["Android", "IOS", "Blackberry", "Windows"];
function callback(title, index) {
Ti.API.info('Selected title=' + title + ' index=' + index);
}
var defaultSelected = 1;
//Here functions is the global file in which my showPicker method is defined.
var pickerShow = functions.showPicker(data, callback, "Mobile OS", defaultSelected);
//Here globals is the file in which my isIos variable is defined.
if (globals.isIos) {
pickerShow.open();
}
Related
My goal is it to create a search ListView with JSON Data.
This is working but I have a tiny problem with the search function.
When I type in a word, it has to be exactly the same word, which is in the Array of the ListView.
The main problem is that I have to type in the correct word.
For example: when the word stackoverflow is one item of the Array, I have to type in stackoverflow to find this item.
But I want to get the Item also when I type in stack or flow or stacko for example.
This is my code:
filterDatasource(event)
{
var searchString = event.nativeEvent.text.toLowerCase();
if (searchString != "")
{
var content = this.state.loadedContent;
var searchResultsArray = [];
for (var i = 0; i < content.length; i++) {
var detailArray = content[i];
const gattung = detailArray.Gattung;
const zugnummer = detailArray.Zugummer;
const ab = detailArray.ab;
const bis = detailArray.bis;
const wochentag = detailArray.Wochentag;
const zeitraum = detailArray.Zeitraum;
if (searchString.contains(ab.toLowerCase())) //searchString.indexOf(ab) >= 0
{
//alert('gefunden');
searchResultsArray.push(detailArray);
this.setState({ dataSource: ds.cloneWithRows(searchResultsArray) });
}
}
}
else {
this.setState({ dataSource: ds.cloneWithRows(this.state.loadedContent) });
}
},
You can do this with indexOf like this:
if (searchString.indexOf(ab.toLowerCase()) > -1)
{
...
}
In Titanium, I have the following code:
var dbWindow = Ti.UI.currentWindow;
var Cloud = require('ti.cloud');
var data = [];
var rowid;
var rowindex;
var table;
var db;
/**
* Creates TableView from database
*/
function makeTable() {
db = Ti.Database.open('myDb');
try {
var rows = db.execute('SELECT * from boatData');
var boatName;
var rowLabel;
while (rows.isValidRow()) {
tableRow = Ti.UI.createTableViewRow({
backgroundSelectedColor : 'red',
rowid : rows.fieldByName('id'),
loa : rows.fieldByName('loa'),
lwl : rows.fieldByName('lwl'),
beam : rows.fieldByName('beam'),
displacement : rows.fieldByName('displacement'),
sailArea : rows.fieldByName('sailArea')
});
boatName = rows.fieldByName('boatName');
rowLabel = Ti.UI.createLabel({
text : boatName,
color : 'black',
font : {
fontSize : 22
},
touchEnabled : false
});
tableRow.add(rowLabel);
tableRow.Label = rowLabel;
data.push(tableRow);
rows.next();
}
rows.close();
db.close();
table = Titanium.UI.createTableView({
data : data,
backgroundColor : 'pink',
headerTitle : 'Boats',
height : '75%',
allowsSelection : true
});
} catch (e) {//database table not found
db.close();
var alertWindow = Titanium.UI.createAlertDialog({
message : 'No data found! Please save data first',
buttonNames : ['OK']
});
alertWindow.addEventListener('click', function(e) {
dbWindow.close();
});
alertWindow.show();
}
}
makeTable();
table.addEventListener('click', function(e) {
rowid = e.rowData.rowid;
rowindex = e.index;
Ti.App.loaBox.value = e.rowData.loa;
Ti.App.lwlBox.value = e.rowData.lwl;
Ti.App.beamBox.value = e.rowData.beam;
Ti.App.displacementBox.value = e.rowData.displacement;
Ti.App.saBox.value = e.rowData.sailArea;
openButton.title = 'Get Data';
selected.text = 'Your selection: ' + e.row.Label.text;
deleteButton.visible = true;
});
var parentView = Titanium.UI.createView({
width : '100%',
height : '100%',
layout : 'vertical'
});
parentView.add(table);
var selectionView = Ti.UI.createView({
top : 5,
height : '10%',
layout : 'vertical'
});
var info = Ti.UI.createLabel({
text : 'Click on a boat name to get data or delete.',
color : 'black',
font : {
fontSize : 25
}
});
var selected = Ti.UI.createLabel({
color : 'red',
font : {
fontSize : 25
}
});
selectionView.add(info);
selectionView.add(selected);
parentView.add(selectionView);
var buttons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var lowerButtons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var openButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Back',
right : 5
});
openButton.addEventListener('click', function(e) {
dbWindow.close();
});
var deleteButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Delete',
left : 5
});
deleteButton.visible = false;
deleteButton.addEventListener('click', function(e) {
var db = Ti.Database.open('myDb');
db.execute('DELETE FROM boatData WHERE id=' + rowid);
db.close();
table.deleteRow(rowindex);
Ti.App.loaBox.value = '';
Ti.App.lwlBox.value = '';
Ti.App.beamBox.value = '';
Ti.App.displacementBox.value = '';
Ti.App.saBox.value = '';
deleteButton.visible = false;
openButton.title = 'Back';
selected.text = '';
});
var saveToCloudButton = Ti.UI.createButton({
backgroundColor : 'pink',
borderColor : 'red',
borderWidth : 2,
font : {
fontSize : 22
},
title : 'Save boats to cloud',
left : 5
});
saveToCloudButton.addEventListener('click', function(e) {
saveToCloud();
});
buttons.add(openButton);
buttons.add(deleteButton);
lowerButtons.add(saveToCloudButton);
parentView.add(buttons);
parentView.add(lowerButtons);
dbWindow.add(parentView);
/**
* Saves database to cloud
*/
function saveToCloud() {
var dbName = 'myDb';
var dbPath;
var dbFile;
if (Ti.Platform.osname == 'android') {
dbPath = 'file:///data/data/' + Ti.App.getID() + '/databases/';
dbFile = Ti.Filesystem.getFile(dbPath + dbName);
} else {
dbPath = Ti.Filesystem.applicationSupportDirectory + '/database/';
dbFile = Ti.Filesystem.getFile( dbPath + dbName + '.sql' );
}
Cloud.Users.secureLogin({
title : 'Sign In'
}, function(e) {
if (e.success) {
Cloud.Files.create({
name : dbName,
file : dbFile
}, function(e) {
if (e.success) {
var file = e.files[0];
alert('Boats successfully backed up to cloud!');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
} else {
alert('Error:\\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
However, for some odd reason, my saveToCloudButton does not appear. I tried manually setting the visibility, and that didn't work. Does anyone know what am I doing wrong?
EDIT: Added full code.
Make the top different for both the views
var buttons = Ti.UI.createView({
top : 5,
layout : 'horizontal'
});
var lowerButtons = Ti.UI.createView({
top : 60,
layout : 'horizontal'
});
Thanks
I figured out my problem. I needed to set height values to buttons and lowerButtons.
I am retrieving the json data using titanium.But the problem is that whenever i calculate the length of json data it says can not read length of null Here is my code:
Ti.UI.setBackgroundColor('#000');
var win1 = Ti.UI.createWindow({
backgroundColor : '#fff',
title : 'Tab 1'
});
var tab1 = Ti.UI.createTab({
icon : 'KS_nav_views.png',
title : 'Tab 1',
window : win1
});
var JsonTable = Ti.UI.createTableView({
height : Ti.UI.FILL,
width : Ti.UI.FILL
});
win1.add(JsonTable);
function getData() {
var myfontsize = '14dp';
// I needed to add this to test
var tableData = [];
var Json, Story;
var xhr = Ti.Network.createHTTPClient({
onload : function() {
var json = JSON.parse(this.responseText);
// declare your variables :-)
//alert(JSON.stringify(Story));
// alert(Story.nombre);
alert(json.length);
// only one . between things
for (var i = 0; i < json.length; i++) {
Story = json[i];
//Ti.API.info('Story', JSON.stringify(Story));
//Ti.API.info('Story.nombre', Story.nombre);
var row = Ti.UI.createTableViewRow({
backgroundColor : 'yellow',
height : '85dp',
width : Ti.UI.FILL
});
var labTitle = Ti.UI.createLabel({
backgroundColor : 'orange',
color : 'black',
font : {
fontSize : myfontsize,
fontWeight : 'bold'
},
height : Ti.UI.SIZE,
left : '25%',
text : Story.nombre,
top : '2%',
width : Ti.UI.FILL
});
row.add(labTitle);
tableData.push(row);
}
JsonTable.setData(tableData);
},
onerror : function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout : 5000
});
JsonTable.addEventListener('click', function(e) {
var index = e.index;
});
xhr.open("GET", "http://aplicaciones4.sct.gob.mx/sibuac_internet/SerEscogeRuta?estados");
xhr.send();
}
var btnGo = Ti.UI.createButton({
title : 'Go'
});
btnGo.addEventListener('click', function(e) {
getData();
});
//win1.setRightNavButton(btnGo);
win1.add(btnGo);
var img = Ti.UI.createImageView({
height : 32,
image : 'activity_indicator.gif',
width : 32
});
//win1.add(img);
var tabGroup = Ti.UI.createTabGroup();
tabGroup.addTab(tab1);
tabGroup.open();
Can you help me in this
Thanks in advance
Try naming the result something other than "json".
Also, there's sloppy var declarations...
"var Json,Story;" << "J"son upper-case, never used
I want autocomplete textbox like if i press a it should shows related words like apple,aeroplane etc.,i want to make like similar google search.is there any control like this operation in ios and android on titanium.Help with examples codes or it's not possible in titanium?
The following code will work for you. Try it and modify as per your need. Here I Used array(searchArray) as data storage(You can replace it with database field or source whatever as per your requirement).
//Table view showing your autocomplete values
var tblvAutoComplete = Ti.UI.createTableView({
width : '100%',
backgroundColor : '#EFEFEF',
height : 0,
maxRowHeight : 35,
minRowHeight : 35,
allowSelection : true
});
//Starts auto complete
txtAutoComplete.addEventListener('change', function(e){
var pattern = e.source.value;
var tempArray = PatternMatch(searchArray, pattern);
CreateAutoCompleteList(tempArray);
});
//You got the required value and you clicks the word
tblvAutoComplete.addEventListener('click', function(e){
txtAutoComplete.value = e.rowData.result;
});
//Returns the array which contains a match with the pattern
function PatternMatch(arrayToSearch, pattern){
var searchLen = pattern.length;
arrayToSearch.sort();
var tempArray = [];
for(var index = 0, len = arrayToSearch.length; index< len; index++){
if(arrayToSearch[index].substring(0,searchLen).toUpperCase() === pattern.toUpperCase()){
tempArray.push(arrayToSearch[index]);
}
}
return tempArray;
}
//setting the tableview values
function CreateAutoCompleteList(searchResults){
var tableData = [];
for(var index=0, len = searchResults.length; index < len; index++){
var lblSearchResult = Ti.UI.createLabel({
top : 2,
width : '40%',
height : 34,
left : '5%',
font : { fontSize : 14 },
color : '#000000',
text : searchResults[index]
});
//Creating the table view row
var row = Ti.UI.createTableViewRow({
backgroundColor : 'transparent',
focusable : true,
height : 50,
result : searchResults[index]
});
row.add(lblSearchResult);
tableData.push(row);
}
tblvAutoComplete.setData(tableData);
tblvAutoComplete.height = tableData.length * 35;
}
This code worked for me in both ios and android. Hope your problems get resolved:D
cool i can give some example for you with android auto address suggestion bar
var search = Titanium.UI.createTextField({
height : '40sp',
hintText : 'Search',
top : '3sp',
right : '0%',
width : '73%',
textAlign : 'left',
font : {
fontFamily : 'Verdana',
fontSize : '13sp',
},
});
your result dispaly as table row
var resulttable = Ti.UI.createTableView({
top : '0%',
left : '0%',
width : '100%',
height : '100%',
separatorColor : '#000000',
});
and add event listner as change and any change call function with your value and if value is empty remove table from your view
search.addEventListener("change", function(event, type) {
Titanium.API.info("in change event listener");
if ('' != search.value) {
tabgroupContentView.add(resulttable);
if (resulttable.data.length > 0) {
for (var i = resulttable.data[0].rows.length - 1; i >= 0; i--) {
resulttable.deleteRow(i);
}
}
auto_complete(search.value);
} else {
tabgroupContentView.remove(resulttable);
}
});
call following function to auto complte
function auto_complete(search_term) {
loader.open("GET", "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + search_term + "&types=geocode&language=en&sensor=true&key=bar blar blar this is my key use ur one");
loader.onload = function() {
var histryresult = eval('(' + this.responseText + ')');
jsonArry = histryresult.predictions;
jsonArryterms = histryresult.terms;
for (var i = 0; i < jsonArry.length; i++) {
var service_row = Ti.UI.createTableViewRow({
height : '70sp',
width : '100%',
backgroundColor : '#ffffff',
backgroundFocusedColor : '#FF8F2F',
backgroundSelectedColor : '#FF8F2F',
hasChild : false
});
var lbl_oderid = Ti.UI.createLabel({
left : '3%',
top : '10%',
text : jsonArry[i].terms[1].value,
color : '#A70CAF',
font : {
fontSize : '17sp',
fontWeight : 'bold'
},
height : 'auto',
width : 'auto'
});
var descriptiontext;
if (jsonArry[i].description == undefined) {
descriptiontext = 'Not Valable';
} else {
descriptiontext = jsonArry[i].description;
}
var lbl_description = Ti.UI.createLabel({
left : '5%',
top : '50%',
text : descriptiontext,
color : '#000000',
font : {
fontSize : '12sp',
},
height : 'auto',
width : 'auto'
});
service_row.add(lbl_oderid);
service_row.add(lbl_description);
service_row.addEventListener('click', function(e) {
var locaName = jsonArry[e.index].description;
if (jsonArry[e.index].description == undefined) {
} else {
reversGeoloader.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=" + locaName + "&sensor=false");
reversGeoloader.onload = function() {
var geoResult = eval('(' + this.responseText + ')');
jsonArry = geoResult.results;
var newlat = jsonArry[0].geometry.location.lat;
var newlng = jsonArry[0].geometry.location.lng;
curentlatitude = newlat;
curentlongitude = newlng;
getReversGeo(curentlatitude, curentlongitude, 'str');
usercurentlocation.setText('Set by serch');
tabTestWindow.close();
};
reversGeoloader.send();
}
});
resulttable.appendRow(service_row);
}
};
loader.send();
}
textField.addEventListener('change', function(e) {
// you can fill a tableView in this event with the suggested data
});
or this tutorial link might solve your problem
AutoCompleteTextField
hope this is my last question for today... O.o
So im filling up a table with input from a user:
var textField = Ti.UI.createTextField({
hintText:"Zoeken over twitter",
backgroundColor:"#fff",
borderColor:"#fff",
borderWidth:1,
borderRadius:10,
left:10,
right:10,
top:10,
height:50
});
Ti.UI.currentWindow.add(textField);
var buttonSearch = Ti.UI.createButton({
title:"Zoeken",
left:10,
right:10,
top:70,
height:50
});
Ti.UI.currentWindow.add(buttonSearch);
buttonSearch.addEventListener("click", function() {
if ( typeof tableview == 'undefined' ) {
} else {
Ti.UI.currentWindow.remove(tableview);
}
var twitterUserName = textField.value;
var httpClient = Ti.Network.createHTTPClient();
httpClient.timeout = 10000;
httpClient.open("GET","http://api.twitter.com/1/statuses/user_timeline.json?count=10&screen_name=" + twitterUserName);
var twitterData = [];
httpClient.onload = function() {
try {
var tweets = JSON.parse(this.responseText);
for (var i=0; i < tweets.length; i++) {
for (var i=0; i < tweets.length; i++) {
var tweetText = tweets[i].text;
var user = tweets[i].user.screen_name;
var avatar = tweets[i].user.profile_image_url;
var created_at = tweets[i].created_at;
var row = Ti.UI.createTableViewRow({hasChild:true,
height:'auto'});
var postView = Ti.UI.createView({
height:'auto',
layout:'vertical',
left:5,
top:5,
bottom:5,
right:5
});
var avatarImageView = Ti.UI.createImageView({
image:avatar,
left:0,
top:0,
height:48,
width:48
});
postView.add(avatarImageView);
var userLabel = Ti.UI.createLabel({
text:user,
left:54,
width:120,
top:-48,
bottom:2,
height:16,
textAlign:'left',
color:'#444444',
font:{fontFamily:'Trebuchet MS',fontSize:14,
fontWeight:'bold'}
});
postView.add(userLabel);
var dateLabel = Ti.UI.createLabel({
text:created_at,
right:0,
top:-18,
bottom:2,
height:14,
textAlign:'right',
width:110,
color:'#444444',
font:{fontFamily:'Trebuchet MS',fontSize:12}
});
postView.add(dateLabel);
var tweetTextLabel = Ti.UI.createLabel({
text:tweetText,
left:54,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
postView.add(tweetTextLabel);
row.add(postView);
twitterData[i] = row;
}
}
var tableview = Titanium.UI.createTableView({data:twitterData,
minRowHeight:58, top:130});
Ti.UI.currentWindow.add(tableview);
} catch(E) {
alert(E);
}
};
httpClient.send();
});
The problem is my second search overwrites my first search witouth removing the table so its displaying 2 tables on top of each other... as u can see i tried to remove the previous table with a typeoff = undefined but this does not work... any ideas on how i can remove the previous filled up table? i tried to do just a remove but this obviously throws errors because the table doesnt exist at first...
This is how I did it.
if (tableview.data.length > 0) {
for (var i = tableview.data[0].rows.length-1; i >= 0; i--) {
tableview.deleteRow(i);
}
}