如何使用搜索和添加功能制作EditText

时间:2015-06-28 18:17:27

标签: android search filter android-edittext

我有一个EditText,它可以作为一个搜索字段,并有一个按钮作为" add-new_item-to-list" -thingy。如果没有过滤器,一切都可以正常工作,但有了它,新项目不会被适配器显示,但会添加到arraylist中。这里有什么建议? (抱歉英文不好)

public class MainActivity extends ActionBarActivity {
ListView listView;
ArrayList<String> player_list = new ArrayList<String>();
ArrayAdapter<String> adapter;
Button addPlayer;
EditText searchPlayer;
String temp_name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.list_view);
    addPlayer = (Button) findViewById(R.id.btn_addPlayer);
    searchPlayer = (EditText) findViewById(R.id.et_searchPlayer);

    player_list.add("bla");
    player_list.add("blubb");

    adapter = new ArrayAdapter<String>(this, R.layout.list_item, player_list);
    listView.setAdapter(adapter);

    addPlayer = (Button) findViewById(R.id.btn_addPlayer);
    addPlayer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            temp_name = searchPlayer.getText().toString();

            if(temp_name.isEmpty() ) {
                searchPlayer.setText("");
                return;
            }
            if(player_list.contains(temp_name)) {
                searchPlayer.setText("");
                Toast.makeText(getBaseContext(), "Player " + temp_name + " already exists", Toast.LENGTH_SHORT ).show();
                return;
            }
            /*android.widget.Filter filter = adapter.getFilter();
            filter = null;*/
            player_list.add(temp_name);
            adapter.notifyDataSetChanged();
            adapter.sort(new Comparator<String>() {
                @Override
                public int compare(String lhs, String rhs) {
                    return lhs.toString().compareTo(rhs.toString());
                }
            });
            searchPlayer.setText("");
        }
    });

    searchPlayer.addTextChangedListener(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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            MainActivity.this.adapter.getFilter().filter(s);
            adapter.notifyDataSetChanged();
        }
    });
}

0 个答案:

没有答案