You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何在Activity内实现对接WordPress接口的搜索框

实现步骤

1. 布局添加搜索输入框

在你的Activity对应的XML布局文件中添加EditText作为搜索框,配置输入法搜索属性:

<EditText
    android:id="@+id/et_search"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="输入关键词搜索文章"
    android:inputType="text"
    android:imeOptions="actionSearch"
    android:maxLines="1"
    android:padding="12dp"/>

这里设置imeOptions="actionSearch"后输入法的回车按钮会变成搜索样式。

2. 调整Retrofit接口定义

不需要手动拼接URL,直接用Retrofit的Query注解动态传参即可,避免手动拼接出现的编码错误:

// 你的WordPress Api接口类
public interface WpApi {
    // 原有基础地址是 https://wahstatus.com/wp-json/ 前提下,定义搜索接口
    @GET("wp/v2/posts/")
    Call<List<Post>> searchPosts(@Query("search") String keyword, @Query("per_page") int perPage);
}

Retrofit会自动把参数拼接到请求地址后面,和你给出的接口格式完全匹配。

3. Activity中添加搜索监听逻辑

在Activity的onCreate方法中给EditText绑定搜索触发监听:

// 先初始化Retrofit实例,和你之前拉取文章的初始化逻辑一致
WpApi wpApi = retrofit.create(WpApi.class);
EditText etSearch = findViewById(R.id.et_search);

etSearch.setOnEditorActionListener((v, actionId, event) -> {
    // 匹配搜索动作:要么是输入法点击了搜索按钮,要么是物理键盘按下了回车
    if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
        String keyword = etSearch.getText().toString().trim();
        if (keyword.isEmpty()) {
            Toast.makeText(this, "请输入搜索关键词", Toast.LENGTH_SHORT).show();
            return true;
        }
        // 触发搜索请求
        performSearch(keyword);
        // 搜索完成后自动收起软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
        return true;
    }
    return false;
});

4. 实现搜索请求方法

复用你原有拉取文章的逻辑即可:

private void performSearch(String keyword) {
    // 可自行添加加载提示逻辑
    wpApi.searchPosts(keyword, 29).enqueue(new Callback<List<Post>>() {
        @Override
        public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
            if (response.isSuccessful() && response.body() != null) {
                // 拿到搜索结果,更新你的文章列表适配器即可
                articleAdapter.setData(response.body());
            }
        }

        @Override
        public void onFailure(Call<List<Post>> call, Throwable t) {
            // 处理请求失败逻辑,比如Toast提示网络错误
        }
    });
}
注意事项
  • 不需要手动对关键词做URL编码,Retrofit的@Query注解会自动处理特殊字符的编码
  • 如果需要默认显示全部文章,传空字符串给search参数即可,WordPress REST API会返回全部文章
  • 可以根据需求添加搜索防抖逻辑,避免用户快速多次触发重复请求

内容的提问来源于stack exchange,提问作者Chand Ninder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 04:30:05