自定义LengthFilter实现对EditText长度的限制和监听

1.对EditText的长度限制和长度监听;
2.避免部分机型上TextWatcher的兼容问题;
3.在长度达到MAX时依然能监听到事件;

import android.text.InputFilter;
import android.text.Spanned;

public class WattLengthFilter implements InputFilter {
   
    private final int mMax;
    private LengthWatch mLengthWatch;

    public WattLengthFilter(int max,LengthWatch lengthWatch) {
   
        mMax = max;
        mLengthWatch = lengthWatch;
    }

    public WattLengthFilter(int max) {
   
        mMax = max;
    }

    /**
     * @param source 输入的文字
     * @param start 输入=0,删除=0
     * @param end 输入=文字的长度,删除=0
     * @param dest 原先显示的内容
     * @param dstart 输入=原光标位置,删除=光标删除结束位置
     * @param dend  输入=原光标位置,删除=光标删除开始位置
     * @return
     */
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现自定义搜索框(EditText)的搜索功能,你可以按照以下步骤进行: 1.在你的布局文件中添加一个EditText和一个搜索按钮(可选)。 ```xml <RelativeLayout ... <EditText ... android:id="@+id/search_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/search_hint" android:imeOptions="action_search" android:inputType="text" android:maxLines="1" android:singleLine="true" /> <ImageButton ... android:id="@+id/search_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:src="@drawable/ic_search" /> </RelativeLayout> ``` 2.在你的Activity(或Fragment)中找到EditText和ImageButton并设置OnClickListener。 ```java public class MainActivity extends AppCompatActivity { private EditText searchEdit; private ImageButton searchBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchEdit = findViewById(R.id.search_edit); searchBtn = findViewById(R.id.search_btn); searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 执行搜索操作 performSearch(); } }); // 设置软键盘的搜索按钮监听器 searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { // 执行搜索操作 performSearch(); return true; } return false; } }); } private void performSearch() { String keyword = searchEdit.getText().toString().trim(); // 执行搜索操作,比如跳转到搜索结果页面 Intent intent = new Intent(this, SearchResultActivity.class); intent.putExtra("keyword", keyword); startActivity(intent); } } ``` 3.在performSearch()方法中执行搜索操作,比如跳转到搜索结果页面,并将搜索关键字作为参数传递给搜索结果页面。 在搜索结果页面中,你可以使用搜索关键字来查询数据库或网络数据,并将结果显示在ListView或RecyclerView中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值