我希望只有在listView
中插入搜索字符串时才会显示EditText
。以下是我的代码......请帮助我,我将非常感激......
public class MainActivity extends AppCompatActivity {
private ListView mSearchNFilterLv;
private EditText mSearchEdt;
private ArrayList<String> mStringList;
private ValueAdapter valueAdapter;
private TextWatcher mSearchTw;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
initData();
valueAdapter = new ValueAdapter(mStringList, this);
mSearchNFilterLv.setAdapter(valueAdapter);
mSearchEdt.addTextChangedListener(mSearchTw);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initData() {
mStringList = new ArrayList<String>();
mStringList.add("one");
mStringList.add("two");
mStringList.add("three");
mStringList.add("four");
mStringList.add("five");
mStringList.add("six");
mStringList.add("seven");
mStringList.add("eight");
mStringList.add("nine");
mStringList.add("ten");
mStringList.add("eleven");
mStringList.add("twelve");
mStringList.add("thirteen");
mStringList.add("fourteen");
mSearchTw = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
valueAdapter.getFilter().filter(s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
if(mSearchEdt.getVisibility() != View.VISIBLE)
mSearchEdt.setVisibility(View.VISIBLE);
}
};
}
private void initUI() {
mSearchNFilterLv = (ListView) findViewById(R.id.list_view);
mSearchEdt = (EditText) findViewById(R.id.txt_search);
}
}
答案 0 :(得分:0)
您可以使用以下代码:
mSearchTw = new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && s.toString().trim().length() > 0) {
mSearchNFilterLv.setVisibility(View.VISIBLE);
} else {
mSearchNFilterLv.setVisibility(View.GONE);
}
}
@Override public void afterTextChanged(Editable s) {
}
};
当输入文本时(输入文本到EditText时),如果文本有1个或更多字符,这将显示ListView。
如果您希望仅在插入结束时更改ListView,请将onTextChanged
内的给定代码移至afterTextChanged
PS:您可以使用与SearchView相同的结构,而不是使用带有查询侦听器的EditText。
<强>更新强>
您可以使用以下代码最初隐藏ListView:
private void initUI() {
mSearchNFilterLv = (ListView) findViewById(R.id.list_view);
mSearchEdt = (EditText) findViewById(R.id.txt_search);
mSearchNFilterLv.setVisibility(View.GONE);
}