4

我是android新手。我只是想爲我的應用做一個簡單的搜索功能。我的應用程序包含一個ListView一個EditText和一個Button供搜索。我ListView內容所使用的是擴展BaseAdapterListview的搜索功能

現在自定義適配器,我想要做的是,我想從ListView搜索任何記錄。例如,如果我的一些記錄,如

從數據庫中列出

優化,運營,數據挖掘,計算機倫理學,計算機系統結構等..

所以,當我鍵入一些唱片名稱,如op

該列表視圖應列出從op...開始的記錄我已經提到了這個,從我得到addTextChangedListener但是,我不知道該怎麼做?

而且,我們能做到這一點相同的功能與button

點擊具有這個任何想法的人?提前致謝。

+1

通過http://stackoverflow.com/a/11009026/1398150 – Harish

+0

看到這個鏈接http://stackoverflow.com/questions/5220551/android-list-view-with-search-functionality – BBdev

回答

7

我曾問過類似的問題還挺而回。這裏:Filtering a ListView with Baseadapter filters text not images。雖然,我的具體問題涉及到GridView,但概念(和代碼)可以替代ListView。

注意:這將是一個漫長的職位,但我覺得有必要爲完整起見(我雖然離開了imports

主要活動(Friends.java

public class Friends extends SherlockActivity { 

    // BUNDLE OBJECT TO GET DATA FROM EARLIER ACTIVITY 
    Bundle extras; 

    // INITIAL ALBUM ID AND NAME 
    String initialUserID; 

    // THE GRIDVIEW 
    GridView gridOfFriends; 

    // THE ADAPTER 
    FriendsAdapter adapter; 

    // ARRAYLIST TO HOLD DATA 
    ArrayList<getFriends> arrFriends; 

    // LINEARLAYOUT TO SHOW THE FOOTER PROGRESS BAR 
    LinearLayout linlaProgressBar; 

    // THE EDITTEXT TO FILTER USERS 
    EditText filterText; 

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

     extras = getIntent().getExtras(); 

     if (extras.containsKey("USER_ID")) { 
      initialUserID = extras.getString("USER_ID"); 
     } else { 
      Toast.makeText(
        getApplicationContext(), 
        "There was a problem getting your Friends Data. Please hit the back button and try again.", 
        Toast.LENGTH_SHORT).show(); 
     } 

     ActionBar actionBar = getSupportActionBar(); 
     actionBar.setDisplayHomeAsUpEnabled(true); 
     actionBar.setDisplayShowHomeEnabled(true); 
     actionBar.setDisplayShowTitleEnabled(true); 
     actionBar.setTitle("Your Friends"); 

     // CAST THE GRIDVIEW 
     gridOfFriends = (GridView) findViewById(R.id.gridFriends); 

     // INSTANTIATE THE ARRAYLIST 
     arrFriends = new ArrayList<getFriends>(); 

     // CAST THE ADAPTER 
     adapter = new FriendsAdapter(Friends.this, arrFriends); 

     // CAST THE LINEARLAYOUT THAT HOLDS THE PROGRESS BAR 
     linlaProgressBar = (LinearLayout) findViewById(R.id.linlaProgressBar); 
     linlaProgressBar.setVisibility(View.GONE); 

     // GET THE LOGGED IN USERS FRIENDS DATA 
     if (initialUserID != null) { 
      new getFriendsData().execute(); 
     } else { 
      Toast.makeText(
        getApplicationContext(), 
        "There was a problem getting your Friends Data. Please hit the back button and try again.", 
        Toast.LENGTH_SHORT).show(); 
     } 

     // CAST THE EDITTEXT AND SETUP FILTERING 
     filterText = (EditText) findViewById(R.id.editFilterList); 
     filterText.addTextChangedListener(filterTextWatcher); 
    } 

    private class getFriendsData extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 

      // SHOW THE BOTTOM PROGRESS BAR (SPINNER) WHILE LOADING THE FRIENDS LIST 
      linlaProgressBar.setVisibility(View.VISIBLE); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 

      try { 
       String query = 
         "SELECT name, uid, pic_big " + 
         "FROM user " + 
         "WHERE uid in " + 
         "(SELECT uid2 FROM friend WHERE uid1=me()) " + 
         "order by name"; 
       Bundle paramGetFriendsList = new Bundle(); 
       paramGetFriendsList.putString("method", "fql.query"); 
       paramGetFriendsList.putString("query", query); 

       String resultFriendsList = Utility.mFacebook.request(paramGetFriendsList); 

       JSONArray JAFriends = new JSONArray(resultFriendsList); 

       getFriends friends; 

       if (JAFriends.length() == 0) { 

       } else { 
        for (int i = 0; i < JAFriends.length(); i++) { 
         JSONObject JOFriends = JAFriends.getJSONObject(i); 

         friends = new getFriends(); 

         // SET FRIENDS ID 
         if (JOFriends.has("uid")) { 
          friends.setFriendID(JOFriends.getString("uid")); 
         } else { 
          friends.setFriendID(null); 
         } 

         // SET FRIENDS NAME 
         if (JOFriends.has("name")) { 
          friends.setFriendName(JOFriends.getString("name")); 
         } else { 
          friends.setFriendName(null); 
         } 

         // SET FRIENDS PROFILE PICTURE 
         if (JOFriends.has("pic_big")) { 
          friends.setFriendProfile(JOFriends.getString("pic_big")); 
         } else { 
          friends.setFriendProfile(null); 
         } 

         arrFriends.add(friends); 

        } 
       } 

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

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 

      // SET THE ADAPTER TO THE GRIDVIEW 
      gridOfFriends.setAdapter(adapter); 

      // HIDE THE BOTTOM PROGRESS BAR (SPINNER) AFTER LOADING THE FRIENDS LIST 
      linlaProgressBar.setVisibility(View.GONE); 
     } 

    } 

    private TextWatcher filterTextWatcher = new TextWatcher() { 

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

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

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

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    }; 
} 

getFriends.java類的ArrayList

public class getFriends { 

    String friendID; 
    String friendName; 
    String friendProfile; 

    // SET FRIENDS ID 
    public void setFriendID(String friendID) { 
     this.friendID = friendID; 
    } 

    // GET FRIENDS ID 
    public String getFriendID() { 
     return friendID; 
    } 

    // SET FRIENDS NAME 
    public void setFriendName(String friendName) { 
     this.friendName = friendName; 
    } 

    // GET FRIENDS NAME 
    public String getFriendName() { 
     return friendName; 
    } 

    // SET FRIENDS PROFILE 
    public void setFriendProfile(String friendProfile) { 
     this.friendProfile = friendProfile; 
    } 

    // GET FRIENDS PROFILE 
    public String getFriendProfile() { 
     return friendProfile; 
    } 
} 

最後,適配器類(FriendsAdapter.java

public class FriendsAdapter extends BaseAdapter implements Filterable { 

    ProgressDialog dialog; 

    Activity activity; 

    LayoutInflater inflater = null; 
    ImageLoader imageLoader; 

    ArrayList<getFriends> arrayFriends; 
    List<getFriends> mOriginalNames; 

    FriendsAdapter(Activity a, ArrayList<getFriends> arrFriends) { 

     activity = a; 

     arrayFriends = arrFriends; 

     inflater = (LayoutInflater) activity 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     imageLoader = new ImageLoader(activity.getApplicationContext()); 
    } 

    public int getCount() { 
     return arrayFriends.size(); 
    } 

    public Object getItem(int position) { 
     return arrayFriends.get(position); 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public void notifyDataSetChanged() { 
     super.notifyDataSetChanged(); 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     View vi = convertView; 
     if (convertView == null) 
      vi = inflater.inflate(R.layout.friends_grid_items, null); 

     ImageView imgProfilePicture = (ImageView) vi.findViewById(R.id.imgProfilePicture); 
     TextView txtUserName = (TextView) vi.findViewById(R.id.txtUserName); 
     FrameLayout mainContainer = (FrameLayout) vi.findViewById(R.id.mainContainer); 


     txtUserName.setText(arrayFriends.get(position).getFriendName()); 

     if (arrayFriends.get(position).getFriendProfile() != null) { 
      imageLoader.DisplayImage(arrayFriends.get(position).getFriendProfile(),imgProfilePicture); 
     } else if (arrayFriends.get(position).getFriendProfile() == null) { 
      imgProfilePicture.setVisibility(View.GONE); 
     } 

     mainContainer.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Intent showFriendsProfile = new Intent(activity.getApplicationContext(), UserProfileNew.class); 
       showFriendsProfile.putExtra("USER_ID", arrayFriends.get(position).getFriendID()); 
       showFriendsProfile.putExtra("NAME", arrayFriends.get(position).getFriendName()); 
       activity.startActivity(showFriendsProfile); 
      } 
     }); 

     return vi; 
    } 

    @Override 
    public Filter getFilter() { 

     Filter filter = new Filter() { 

      @SuppressWarnings("unchecked") 
      @Override 
      protected void publishResults(CharSequence constraint, 
        FilterResults results) { 

       arrayFriends = (ArrayList<getFriends>) results.values; 
       notifyDataSetChanged(); 
      } 

      @Override 
      protected FilterResults performFiltering(CharSequence constraint) { 

       FilterResults results = new FilterResults(); 
       ArrayList<getFriends> FilteredArrayNames = new ArrayList<getFriends>(); 

       if (mOriginalNames == null) { 
        mOriginalNames = new ArrayList<getFriends>(arrayFriends); 
       } 
       if (constraint == null || constraint.length() == 0) { 
        results.count = mOriginalNames.size(); 
        results.values = mOriginalNames; 
       } else { 
        constraint = constraint.toString().toLowerCase(); 
        for (int i = 0; i < mOriginalNames.size(); i++) { 
         getFriends dataNames = mOriginalNames.get(i); 
         if (dataNames.getFriendName().toLowerCase() 
           .contains(constraint.toString())) { 
          FilteredArrayNames.add(dataNames); 
         } 
        } 

        results.count = FilteredArrayNames.size(); 
        // System.out.println(results.count); 

        results.values = FilteredArrayNames; 
        // Log.e("VALUES", results.values.toString()); 
       } 

       return results; 
      } 
     }; 

     return filter; 
    } 
} 

您可以使用此概念,代替你的ListView控件。我已經在其他地方使用了ListView並按照它的原樣工作。不幸的是,我無法在公開的論壇上提供該代碼。希望這可以幫助你。再次,一個非常冗長的帖子無疑,但我相信是必要的。

+0

@Newbie_to_Android:嘗試用getFilter()方法替換上面代碼中的位。您可能需要對代碼進行一些更改以適應代碼中的概念。例如,您將另一個List(檢查mOriginalName List <>)以保存過濾的數據,然後調用notifyDataSetChanged()以顯示在您的列表中。 –

+0

我正在爲我的ArrayList使用名爲getFriends的自定義類。就像我說的,你將不得不做幾個替換。你可以將主要活動代碼添加到帖子中嗎?我認爲這會讓它更容易。 –

+0

在getFilter()方法中,嘗試用「String」替換getFriends。 –

0

你可以使用自動完成者與Editext和使用不斷更新的名單適配器,也see

<yourEditText>.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 
      <requery/filter your adapter then set it to your listview> 
      } 

      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
       // TODO Auto-generated method stub 

      } 

      @Override 
      public void afterTextChanged(Editable s) { 
       // TODO Auto-generated method stub 

      } 
     }); 
+0

感謝您的幫助。我得到了答案。 – Kumar