突出显示当前选定的文本字段 - 最佳方法

时间:2015-03-10 19:43:15

标签: javascript android ios titanium titanium-alloy

我想在手机上实现这样的效果(ios + android): http://i.imgur.com/6zaTdRd.png

当前选定的文本字段具有蓝色图标+下划线

所以我的框架缺乏对任何类型的位图图像的灰度缩放的支持,所以我需要在两个图像之间交换以实现这种效果。

我目前的实现如下:

请注意钛合金MVC框架,但我猜测基本逻辑应该是类似的。

我会监听模糊/焦点事件以切换当前图像

$.firstNameField.addEventListener('focus', function(e){
    swapImages($.firstNameField.getParent());
});

$.lastNameField.addEventListener('focus', function(e){
swapImages($.lastNameField.getParent());
});

然后我像这样交换图像:

/**
* Swaps between the images (..._0 and ..._1) of an ImageView nested in a
TableRow  
* ..._0 Greyscale image
* ..._0 Colour image
* @param e current TableViewRow
*/
function swapImages(e){
    var imagePathSplit = (e.children[0].image).split('_'); 
    var newImagePath = null;

    if(imagePathSplit[1] == "0.png")
        newImagePath = imagePathSplit[0] + "_1.png";
    else
        newImagePath = imagePathSplit[0] + "_0.png";

    e.children[0].image = newImagePath;
    return;
}

这看起来不是很好,特别是因为我需要更多具有此功能的字段,我还想在字段之间实现tabbing(使用Return key = NEXT),这将进一步增加气球以增加1个事件监听器每场。

理想情况下会如何完成这样的事情?我可以想到一种只在数组形式的代码中创建字段的方法,这有助于简化问题(不再对父母/子女来说太过分了,但这仍然会使用相当多的听众进行切换?

编辑:忘记添加textFields设置的方式:

<TableView id="paypalTable">
<TableViewSection>
    <TableViewRow id="firstNameView" class="tableRow">
        <ImageView id="firstNameIcon" class="textFieldIcon"/>
        <TextField id="firstNameField" class="textField"/>
    </TableViewRow>

1 个答案:

答案 0 :(得分:1)

我在我的一个项目中尝试过类似的东西。虽然我有一个Alloy项目,但我必须使用经典方法来获得我想要的行为。

在我的控制器中:

var textFields            = [];
var yourTextFieldsArray   = [];

for (var i = 0; i < yourTextFieldsArray; i++) {
    //Set the selected state to false initially. Maybe you need another command for it.
    textFieldIsSelected[i] = false;
    //create your new view
    textFields[i] = Ti.UI.createView({
        top : topValues[i],
        width : Titanium.UI.FILL,
        height : height,
        id : i + 1,
        touchEnabled : true
    });
    textFields[i].addEventListener('click', function(e) {
        //Check the source id
        if (e.source.id - 1 > -1) {
            //use your function swapImages(e.source.id). Notice the slightly different parameter since you do not need the complete event.
            swapImages(e.source.id);
        }
}

function swapImages(id){
    //Check the the path variable as you did
    var imagePathSplit = (textFields[i-1].image).split('_'); 
    var newImagePath = null;

    if(imagePathSplit[1] == "0.png")
        newImagePath = imagePathSplit[0] + "_1.png";
    else
        newImagePath = imagePathSplit[0] + "_0.png";

    textFields[i-1].image = newImagePath;
}

此方法允许您为每个属性使用相同的事件侦听器。

请注意,我的ID从1开始,不是为0.这是因为我必须为图像实现此类行为,而ImageViews不接受id=0。我的猜测是TextViews也没有这样做,所以你应该坚持下去。进一步注意,您需要递减id以获取textFields数组中的相应对象。否则你会得到一个越界错误。

您应该为NEXT事件再创建一个事件侦听器。以与第一个eventListener相同的方式实现它。也许代码并不完美,因为我是从记忆中写的。如果有任何问题,请随时在评论中提出。