-2

编辑:这个答案不适合我,我需要根据我的情况更多的答案,谢谢

当我调用列表视图时如何使用自定义列表视图进行搜索我不使用它传递数组。现在我想对姓名手机号码进行搜索,请帮助我如何实现?姓名和手机号码有复选框,如果姓名复选框被选中然后搜索姓名如果手机号码复选框被选中然后搜索手机号码

public class AndroidJSONParsingActivity extends ListActivity {

// JSON Node names
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ID = "id";
private static final String TAG_PHONE_MOBILE = "mobile";
EditText search;
int textlength=0;
ListView lv;
 ArrayList<String> text_sort = new ArrayList<String>();
 ArrayList<Integer> image_sort = new ArrayList<Integer>();
 ListViewAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //access the controls 
    showList();
    CheckBox Name = (CheckBox) findViewById(R.id.checkBox1);
    CheckBox Mobile = (CheckBox) findViewById(R.id.checkBox2);

    if(Name.isChecked()==true){
        //search on name
    }
    if(Mobile.isChecked()==true){
        //search on mobile
    }
    Button addnew = (Button) findViewById(R.id.btnAddNew);
    // selecting single ListView item
            lv = getListView();
    addnew.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(), Insrt.class);
            startActivity(intent);
        }
    });
    search = (EditText)findViewById(R.id.etSearch);
    search.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
        int count) {

            adapter.getFilter().filter(s);
            adapter.notifyDataSetChanged();
        }
        });


}



private void showList() {
    // TODO Auto-generated method stub
    ListAdapter adapter = new ListViewAdapter(this);
    setListAdapter(adapter);



    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long ids) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
            String id = ((TextView) view.findViewById(R.id.id)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            in.putExtra(TAG_ID, id);
            startActivity(in);

        }
    });
}





}

现在我想对NAME和手机号码进行搜索,请帮助我是如何做到的?请帮助

 public class ListViewAdapter extends ArrayAdapter {
private Filter filter;

public ListViewAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    // TODO Auto-generated constructor stub
}
@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}
// url to make request
private static String url = "https://abc.net/api/api/employees/";
// JSON Node names
ArrayList<String> TAG_ID= new ArrayList<String>();
ArrayList<String> TAG_NAME= new ArrayList<String>();
ArrayList<String> TAG_EMAIL= new ArrayList<String>();
ArrayList<String> TAG_PHONE_MOBILE= new ArrayList<String>();
static Context context;
JSONArray employee = null;
String id,name,email,mobile;
ArrayList<Integer> close =new ArrayList<Integer>();
private Activity activity;
ViewHolder view;

//constructor
    public ListViewAdapter(Activity activity) 
    {
    super(context, 0);
    this.activity = activity;

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);



    try {
        // Getting Array of Employee
        employee = json.getJSONArray("Employee");

        // looping through All Employee
        for(int i = 0; i < employee.length(); i++)
        {
        JSONObject c = employee.getJSONObject(i);

            // Storing each json item in variable
            id = String.valueOf(c.getInt("Id"));
            name = c.getString("Name");
            email = c.getString("Email");
            mobile = c.getString("Mobile");

            //adding all get values into array
            if(name!="null"&&mobile!="null"){
            TAG_NAME.add(name);
            TAG_ID.add(id);
            TAG_EMAIL.add(email);
            TAG_PHONE_MOBILE.add(mobile);
            close.add(R.drawable.close);
            }


        }
    } catch (JSONException e) {
        e.printStackTrace();
    }



}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return TAG_NAME.size();
}

@Override
public Object getItem(int paramInt) {
    // TODO Auto-generated method stub
    return TAG_NAME.size();
}

@Override
public long getItemId(int paramInt) {
    // TODO Auto-generated method stub
    return 0;
}

public static class ViewHolder {
    public ImageView deleteButtonImg;
    public TextView name,email,mobile,id;



}

@Override
public View getView(final int paramInt, View paramView, final ViewGroup paramViewGroup) {
    // TODO Auto-generated method stub

    LayoutInflater inflator = activity.getLayoutInflater();
    if (paramView == null) {
        view = new ViewHolder();
        paramView = inflator.inflate(R.layout.list_item, null);

        view.name = (TextView) paramView.findViewById(R.id.name);
        view.email = (TextView) paramView.findViewById(R.id.email);
        view.mobile = (TextView) paramView.findViewById(R.id.mobile);
        view.id = (TextView) paramView.findViewById(R.id.id);
        view.deleteButtonImg = (ImageView) paramView.findViewById(R.id.ibclose);
        paramView.setTag(view);


    } else {
        view = (ViewHolder) paramView.getTag();
    }

    view.name.setText(TAG_NAME.get(paramInt));
    view.email.setText(TAG_EMAIL.get(paramInt));
    view.mobile.setText(TAG_PHONE_MOBILE.get(paramInt));
    view.deleteButtonImg.setImageResource(close.get(paramInt));
    view.id.setText(TAG_ID.get(paramInt));
    view.name.setFocusableInTouchMode(false);
    view.name.setFocusable(false);
    view.deleteButtonImg.setFocusableInTouchMode(false);
    view.deleteButtonImg.setFocusable(false);
    view.deleteButtonImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();
            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
                        HttpDelete httpDelete = new HttpDelete("https://abc.net/api/api/employees/"+TAG_ID.get(paramInt));

                        httpDelete.setHeader("content-type", "application/json");
                        JSONObject data = new JSONObject();

                        try {
                            data.put("Id", TAG_ID.get(paramInt));

                        /*StringEntity entity = new StringEntity(data.toString());
                        httpPost.setEntity(entity);*/

                        HttpResponse response = httpClient.execute(httpDelete);
                        String responseString = EntityUtils.toString(response.getEntity());
                        //int workoutId = responseJSON.getInt("id");
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                         TAG_NAME.remove(paramInt);
                         TAG_EMAIL.remove(paramInt);
                         TAG_PHONE_MOBILE.remove(paramInt);
                         TAG_ID.remove(paramInt);
                         close.remove(paramInt);

            notifyDataSetChanged();

        }
    });

    return paramView;
}
private class PkmnNameFilter extends Filter
{

@Override
protected FilterResults performFiltering(CharSequence constraint) {
    FilterResults results = new FilterResults();
    // We implement here the filter logic
    if (constraint == null || constraint.length() == 0) {
        // No filter implemented we return all the list
        results.values = TAG_NAME;
        results.count = TAG_NAME.size();
    }
    else {
        // We perform filtering operation
        List<Object> nPlanetList = new ArrayList<Object>(TAG_NAME);

        for (Object p : TAG_NAME) {
            if (((Scheme) p).getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
                nPlanetList.add(p);
        }

        results.values = nPlanetList;
        results.count = nPlanetList.size();

    }
    return results;
}
  @Override
  protected void publishResults(CharSequence constraint, FilterResults results) {
       final ArrayList<String> localItems = (ArrayList<String>) results.values;
          notifyDataSetChanged();
          clear();
          for (Iterator<String> iterator = localItems.iterator(); iterator
                  .hasNext();) {
              String gi = (String) iterator.next();
              add(gi);
          }
  }
}

}

我在谷歌上搜索但我不明白如何实现?

4

2 回答 2

1

您需要将在 editext 中键入的字符串传递给您的过滤器

youradapter.getFilter().filter(s);
youradapter.notifyDataSetChanged();

在适配器类中覆盖 getFilter() 和 performFiltering(params)

  @Override
  public Filter getFilter() {
   return new Filter() {
        @Override
       protected void publishResults(CharSequence constraint, FilterResults results)                  {
           if (results != null && results.count >= 0) {
              //set reeulst
           } else {
               // set original values
           }

           notifyDataSetInvalidated();
       }



      @Override
       protected FilterResults performFiltering(CharSequence constraint) {
           FilterResults result = new FilterResults();
           if (!TextUtils.isEmpty(constraint)) {
                  ArrayList<type> foundItems = new ArrayList<type>();
                       //do something
                       //filter resutls 
                 }

               result.count = foundItems.size();//search results found return count
               result.values = foundItems;// return values

           else
           {
               result.count=-1;// no search results found
           }
              return  result;
      } 

编辑:

  public class MainActivity extends Activity {
EditText search;
ListView lv;
CustomAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView) findViewById(R.id.lv);
    adapter = new CustomAdapter(this,0);
    search = (EditText)findViewById(R.id.editText1);
    search.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
        int count) {

            adapter.getFilter().filter(s);
            adapter.notifyDataSetChanged();

        }
        });


}

  class CustomAdapter extends ArrayAdapter
  {
public CustomAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    // TODO Auto-generated constructor stub
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    return super.getView(position, convertView, parent);
}

@Override
public Filter getFilter() {
    // TODO Auto-generated method stub
    return super.getFilter();
}   
    }
    }

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

 <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:ems="10" />

 <ListView
    android:id="@+id/lv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText1" >

  </ListView>  
  </RelativeLayout>

编辑 :

这是工作代码的链接

使用 EditText 在 ListView 中搜索

我不知道是否有人会为你编码。但是,如果您尝试,您应该能够进行更改以在您的代码中实现相同的功能..

在此处输入图像描述

在此处输入图像描述

于 2013-04-12T06:57:35.393 回答
1

Rohit - 抱歉,但乍一看,我发现了一些潜在的问题。没有时间构建和运行您的代码,我只能猜测您的具体要求。我将讨论前两个重构机会。我的直觉认为你会在这个过程中找到答案。

首先,您在活动初始​​化之前调用了一个名为“showList()”的方法。(在我看来,您应该稍后再调用此方法。例如,在 onResume 中。)

然后,您将创建在 onCreate 运行后将不在范围内的局部引用变量(每个实例仅发生一次)。

顺便说一句,当内联类定义(例如新的 View.OnClickListener)解析为适当的命名类和/或类的实例是成员变量时,我发现这类问题更容易解决。如果此类更改可能会产生内存管理问题,您可以在程序按用户预期运行后进行优化。

祝你好运!

-布兰登

于 2013-04-22T02:17:18.080 回答