首页 > 解决方案 > JetPack Compose:执行 KeyBoardAction

问题描述

我正在使用撰写版本1.0.0-beta05ImeAction.Search单击键盘图标时,我正在尝试执行搜索。我试着做如下。

TextField(
    modifier = Modifier
        .fillMaxWidth(.9f)
        .padding(8.dp)
        .background(MaterialTheme.colors.surface),
    value = query,
    onValueChange = { userInput ->
        viewModel.onQueryChanged(userInput)
    },
    label = { Text(text = "Search") },
    textStyle = TextStyle(color = MaterialTheme.colors.onSurface),
        keyboardOptions = KeyboardOptions(
            keyboardType = KeyboardType.Text,
            imeAction = ImeAction.Search
        ),
    leadingIcon = {
        Icon(
            imageVector = Icons.Filled.Search,
            contentDescription = null
        )
    },
    onImeActionPerformed = { action, softKeyboardController ->
        if (action == ImeAction.Search) {
            viewModel.executeSearch(query)  
            softKeyboardController.hideSoftwareKeyboard()
        }
    },
)

但是,None of the following functiosn can be called with arguments suppplied.我检查了一下,发现这onImeActionPerformed不是TextField()论点之一。所以我尝试使用 KeyBoardActions,如下所示:

TextField( 
    modifier = Modifier
        .fillMaxWidth(.9f)
        .padding(8.dp)
        .background(MaterialTheme.colors.surface),
    value = query,
    onValueChange = { userInput ->
        viewModel.onQueryChanged(userInput)
    },
    label = { Text(text = "Search") },
    textStyle = TextStyle(color = MaterialTheme.colors.onSurface),  
    keyboardOptions = KeyboardOptions(
        keyboardType = KeyboardType.Text,
        imeAction = ImeAction.Search
    ),
    leadingIcon = {
        Icon(
            imageVector = Icons.Filled.Search,
            contentDescription = null
        )
    },
    keyboardActions = KeyboardActions(
        onSearch = {
            viewModel.executeSearch(query)
        }
    )
)

这是我的ViewModel

@HiltViewModel
class RecipeListViewModel @Inject constructor(
    private val repository: RecipeRepository,
    @Named("auth_token") private val authToken: String
) : ViewModel() {

    val recipes: MutableState<List<Recipe>> = mutableStateOf(ArrayList())
    val query = mutableStateOf("")

    init {
        executeSearch(query.value)
    }

    fun executeSearch(query: String) {
        viewModelScope.launch {
            val result = repository.search(
                token = authToken,
                page = 1,
                query = "beef"
            )
            recipes.value = result
        }
    }

    fun onQueryChanged(query:String){
        this.query.value = query
    }
}

我的目标是执行搜索和更新 UI。我被困在这里

标签: androidandroid-jetpack-compose

解决方案


onImeActionPerformed 已弃用1.0.0-alpha12。

使用KeyboardActions.
就像是:

   val keyboardController = LocalSoftwareKeyboardController.current

    keyboardActions = KeyboardActions(
        onSearch = {
            //...
            keyboardController?.hide()
        }
    )

推荐阅读