搜索列表视图

时间:2016-05-02 16:13:41

标签: java android xml

我想让我的listview可搜索我在他们开始输入的时候在我想要的列表上面放了一个editText,开始过滤文本。

我的列表适配器

public class ClienteSearchListAdapter extends ArrayAdapter<Cliente> {

protected static final String LOG_TAG = ClienteListAdapter.class.getSimpleName();

private List<Cliente> items;
private int layoutResourceId;
private Context context;

public ClienteSearchListAdapter(Context context, int layoutResourceId, List<Cliente> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.items = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    row = inflater.inflate(layoutResourceId, parent, false);

    AtomPaymentHolder holder = new AtomPaymentHolder();
    holder.cliente = items.get(position);
    holder.searchCliente = (ImageButton)row.findViewById(R.id.actionsearch_button);
    holder.searchCliente.setTag(holder.cliente);

    holder.nomecliente = (TextView)row.findViewById(R.id.nomecliente);
    holder.ntele = (TextView)row.findViewById(R.id.ntelecliente);

    row.setTag(holder);

    setupItem(holder);
    return row;
}

private void setupItem(AtomPaymentHolder holder) {
    holder.nomecliente.setText(holder.cliente.getNomeCompleto());
    holder.ntele.setText(String.valueOf(holder.cliente.getNtelemovel()));
}

public static class AtomPaymentHolder {
    Cliente cliente;
    TextView nomecliente;
    TextView ntele;
    ImageButton searchCliente;
}
}

我的活动:

public class search_cli extends BaseNavegationActivity {

private ClienteSearchListAdapter adapter;

List<Cliente> cliente;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_cli);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    ServerRequests serverRequests = new ServerRequests(this);
    serverRequests.FetchClienteDataInBackground(userLocalStore.getLoggedInUser(), new GetContactosCallBack() {
        @Override
        public void done(List<Cliente> returnUser) {
            try {
                if (returnUser == null) {
                    throw new Exception("Não existem dados ou ocorreu um erro no servidor\nTente novamente mais tarde.");//Nao existem*
                }
                for (Cliente cliente : returnUser) {
                    adapter.add(cliente);
                }
            }
            catch (Exception erro){
                showError(erro);
            }
        }
    });

    cliente = new ArrayList<>();

    setupListViewAdapter();

}

public void actionOnClickHandler( final View v) {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        try{
            final Cliente itemToaction = (Cliente) v.getTag();
             this will do something

        }
        catch (Exception er)
        {
            showError();
        }
    }
}

private void setupListViewAdapter() {
    adapter = new ClienteSearchListAdapter(search_cli.this, R.layout.clientesearch, new ArrayList<Cliente>());
    ListView atomPaysListView = (ListView)findViewById(R.id.EnterPays_atomPaysList);
    atomPaysListView.setAdapter(adapter);
}

private void showError(Exception ero){
    AlertDialog.Builder dialogBuilder=new AlertDialog.Builder(this);
    dialogBuilder.setMessage("Ocorreu um erro:\n" + ero.getMessage());
    dialogBuilder.setPositiveButton("ok", null);
    dialogBuilder.show();
}

private void showError(){
    android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(search_cli.this);
    dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
    dialogBuilder.setPositiveButton("Ok", null);
    dialogBuilder.show();
}
}

我的列表布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:listPreferredItemHeightSmall"
android:orientation="horizontal"
android:showDividers="middle"
android:divider="?android:dividerVertical"
android:dividerPadding="8dp"
android:gravity="center">


<TextView android:id="@+id/nomecliente"
    style="?android:textAppearanceMedium"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:paddingLeft="?android:listPreferredItemPaddingLeft" />

<TextView android:id="@+id/ntelecliente"
    style="?android:textAppearanceMedium"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content" />


<ImageButton android:id="@+id/actionsearch_button"
    android:layout_width="48dp"
    android:layout_height="match_parent"
    android:onClick="actionOnClickHandler"
    android:src="@drawable/ic_action_folder_open"
    android:background="?android:selectableItemBackground"
    android:contentDescription="@string/action_search_item" /></LinearLayout>

我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".search_cli"
android:id="@+id/search_cli_container"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchname"
    android:layout_marginTop="10dp"
    android:hint="Pesquisar"/>
<ListView
    android:id="@+id/EnterPays_atomPaysList"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    tools:listitem="@layout/clientesearch"
    android:layout_below="@+id/layout_search_cli" >
</ListView>

我找到了一些教程,但它并没有为我工作,因为我无法适应我当前的代码,所以如果有人可以帮助我,那将是apreciate。如果你问的是actionOnClickerHandler忽略了什么,那将会转到另一个活动

1 个答案:

答案 0 :(得分:0)

添加addtextchangelistener,如下所示:

</teacher_mode>

更新你的适配器:

// Capture Text in EditText
        editsearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                    int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub
            }
        });

您可以更新条件 如果(wp.getNomeCompleto.toLowerCase(Locale.getDefault())。包含(charText)) 作为你的要求。

更新:

public class ClienteSearchListAdapter extends ArrayAdapter<Cliente> {

protected static final String LOG_TAG = ClienteListAdapter.class.getSimpleName();

private List<Cliente> items;
private int layoutResourceId;
private Context context;
private ArrayList<Cliente> arraylist;

public ClienteSearchListAdapter(Context context, int layoutResourceId, List<Cliente> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.items = items;
    this.arraylist = new ArrayList<Cliente>();
    this.arraylist.addAll(items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    row = inflater.inflate(layoutResourceId, parent, false);

    AtomPaymentHolder holder = new AtomPaymentHolder();
    holder.cliente = items.get(position);
    holder.searchCliente = (ImageButton)row.findViewById(R.id.actionsearch_button);
    holder.searchCliente.setTag(holder.cliente);

    holder.nomecliente = (TextView)row.findViewById(R.id.nomecliente);
    holder.ntele = (TextView)row.findViewById(R.id.ntelecliente);

    row.setTag(holder);

    setupItem(holder);
    return row;
}

private void setupItem(AtomPaymentHolder holder) {
    holder.nomecliente.setText(holder.cliente.getNomeCompleto());
    holder.ntele.setText(String.valueOf(holder.cliente.getNtelemovel()));
}

public static class AtomPaymentHolder {
    Cliente cliente;
    TextView nomecliente;
    TextView ntele;
    ImageButton searchCliente;
}

public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        items.clear();
        if (charText.length() == 0) {
            items.addAll(arraylist);
        } 
        else 
        {
            for (Cliente wp : arraylist) 
            {
                if (wp.getNomeCompleto.toLowerCase(Locale.getDefault()).contains(charText)) 
                {
                    items.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
}

还更新以下方法:

serverRequests.FetchClienteDataInBackground(userLocalStore.getLoggedInUser(), new GetContactosCallBack() {
        @Override
        public void done(List<Cliente> returnUser) {
            try {
                if (returnUser == null) {
                    throw new Exception("Não existem dados ou ocorreu um erro no servidor\nTente novamente mais tarde.");//Nao existem*
                 cliente.addAll(returnUser);
                 adapter.notifyDatasetChanged();
                }

            }
            catch (Exception erro){
                showError(erro);
            }
        }
    });