在更改的文本上更改EditText的宽度

时间:2012-09-26 16:03:35

标签: android android-edittext

我正在尝试更改搜索栏的宽度,以便当用户开始输入时,搜索栏会显示“收藏夹”按钮,但是当他们没有输入时,会显示收藏夹按钮。

这是我现在拥有的

searchBar.addTextChangedListener(new TextWatcher(){         
        public void afterTextChanged(Editable arg0){
            menuItems.this.adapter.getFilter().filter(arg0);
            if(searchBar.getText().length() <= 0){

                searchBar.getLayoutParams().width = 280;
                favButton.getLayoutParams().width = 15;
            }
            else{                   
                searchBar.getLayoutParams().width = 295;
                favButton.getLayoutParams().width = 0;
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {               
        }
    }); 

2 个答案:

答案 0 :(得分:1)

如果您的目标是隐藏/显示视图(在您的情况下为Fav按钮),我建议使用不同的方法。

试试这个:

if(searchBar.getText().length() <= 0) {
    searchBar.getLayoutParams().width = 280;
    favButton.setVisibility(View.Visible);
} else {                   
    searchBar.getLayoutParams().width = 295;
    favButton.setVisibility(View.GONE);
}

很难说在不知道布局的情况下它的效果如何,但使用修复尺寸大小通常不是一个很好的做法。

答案 1 :(得分:0)

您需要在AndroidManifest.xml中设置layout_width元素,如下所示,

android:layout_width="fill_parent"

只需在EditText中设置此元素,如下所示,

<EditText android:id="@+id/txtURL" android:layout_width="fill_parent"
...
...>
</EditText>