所以我安装了自动完成插件:
tns plugin add nativescript-ui-autocomplete
并在我的XML中添加了视图:
<Page xmlns="http://schemas.nativescript.org/tns.xsd"
xmlns:au="nativescript-ui-autocomplete" loaded="pageLoaded" class="page">
<StackLayout class="p-20">
<au:RadAutoCompleteTextView id="autoComplete" items="{{ items }}" suggestMode="Suggest" displayMode="Token">
<au:RadAutoCompleteTextView.suggestionView>
<au:SuggestionView suggestionViewHeight="300">
<au:SuggestionView.suggestionItemTemplate>
<StackLayout tap="{{tokenSelected}}">
<Label text="{{ text }}" />
</StackLayout>
</au:SuggestionView.suggestionItemTemplate>
</au:SuggestionView>
</au:RadAutoCompleteTextView.suggestionView>
</au:RadAutoCompleteTextView>
</StackLayout>
我还在建议的stacklayout的tap事件中添加了一个函数,并将项添加到RadAutoCompleteTextView:
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var autocompleteModule = require("nativescript-ui-autocomplete");
var page;
var pageData = new Observable();
var items = new ObservableArray([]);
exports.pageLoaded = function (args) {
page = args.object;
page.bindingContext = pageData;
const persons = ["Sjoerd Pottuit", "Sjoerd Pottuit", "David Lamp", "Ryan Tulp"];
for (var i = 0; i < persons.length; i++) {
items.push(new autocompleteModule.TokenModel(persons[i]));
};
pageData.set("items", items);
pageData.set("tokenSelected", tokenSelected);
};
function tokenSelected(args) {
//how to know which Sjoerd Pottuit is selected?
const person = args.view.bindingContext.text;
console.dir(args);
console.log(person); // returns: JS: Sjoerd Pottuit
};
问题是tokenSelected函数不返回所选项的索引,RadAutoCompleteTextView只接受TokenModel类型的对象,它只能包含要显示为搜索结果的文本和图像。
我想要索引,这样我就可以从另一个数组中获取更多来自所选人员的数据。
console.dir(参数);回:
JS: ==== object dump start ====
JS: type: "1"
JS: view: StackLayout(10)@file:///app/main-page.xml:8:25;
JS: android: MotionEvent { action=ACTION_UP, actionButton=0, id[0]=0, x[0]=230.0, y[0]=44.0, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=617931691, downTime=617931598, deviceId=3, source=0x1002 }
JS: ios: "undefined"
JS: object: StackLayout(10)@file:///app/main-page.xml:8:25;
JS: eventName: "tap"
JS: ==== object dump end ====
我通过将这段代码添加到我的pageLoaded函数,在RadAutoCompleteTextView的itemLoading事件中为item的包装器添加了一个id:
const autoComplete = page.getViewById("autoComplete");
autoComplete.on("itemLoading", (args) => {
const stackLayout = args.view;
stackLayout.id = args.index;
});
这样我就可以通过在tokenSelected函数(args.view.id)中检索所选视图的id来获取索引。我将此索引用于另一个包含有关所选人员的更多数据的数组。
function tokenSelected(args) {
const person = page.bindingContext.personData[args.view.id];
};