2014-01-22 6 views
-5

У меня динамический список в моем приложении. Я хочу добавить в него функцию поиска, так что, когда я ввожу слово в строку поиска, в моем представлении списка будут отображаться только те слова, которые соответствуют введенным мной словам. Любая идея и помощь будут высоко оценены.Как добавить функцию поиска в мое приложение?

Это моя активность:

public class Artists extends ListActivity { 



private static String url = "http://api.androidhive.info/contacts/"; 

// JSON Node names 
private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 
private static final String TAG_ADDRESS = "address"; 
private static final String TAG_GENDER = "gender"; 
private static final String TAG_PHONE = "phone"; 
private static final String TAG_PHONE_MOBILE = "mobile"; 
private static final String TAG_PHONE_HOME = "home"; 
private static final String TAG_PHONE_OFFICE = "office"; 

// contacts JSONArray 
JSONArray contacts = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.artists); 

    // Hashmap for ListView 
      ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); 

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

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

      try { 
       // Getting Array of Contacts 
       contacts = json.getJSONArray(TAG_CONTACTS); 

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

        // Storing each json item in variable 
        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String email = c.getString(TAG_EMAIL); 
        String address = c.getString(TAG_ADDRESS); 
        String gender = c.getString(TAG_GENDER); 

        // Phone number is agin JSON Object 
        JSONObject phone = c.getJSONObject(TAG_PHONE); 
        String mobile = phone.getString(TAG_PHONE_MOBILE); 
        String home = phone.getString(TAG_PHONE_HOME); 
        String office = phone.getString(TAG_PHONE_OFFICE); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_ID, id); 
        map.put(TAG_NAME, name); 
        map.put(TAG_EMAIL, email); 
        map.put(TAG_PHONE_MOBILE, mobile); 

        // adding HashList to ArrayList 
        contactList.add(map); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      /** 
      * Updating parsed JSON data into ListView 
      * */ 
      ListAdapter adapter = new SimpleAdapter(this, contactList, 
        R.layout.row_artists, 
        new String[] { TAG_NAME }, new int[] { 
          R.id.tv_row_artists }); 

      setListAdapter(adapter); 
      // selecting single ListView item 
      ListView lv = getListView(); 
     // ListView lv = (ListView) findViewById(R.id.lv_chart_listview); 

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

       @Override 
       public void onItemClick(AdapterView<?> parent, View view, 
         int position, long id) { 
        // getting values from selected ListItem 

       } 
      }); 

    ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart); 
    ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease); 

    ll_artists_chart.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(getBaseContext(), MainActivity.class); 
      startActivity(intent); 
      finish(); 
     } 
    }); 

    ll_artists_newrelease.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(getBaseContext(), NewReleases.class); 
      startActivity(intent); 
      finish(); 
     } 
    }); 
} 

} 

и это мой Xml файл:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<LinearLayout 
     android:id="@+id/ll_artists_topheader" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/top_bar1" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/tv_artists_triplevmusic" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center_horizontal" 
      android:text="TripleVMusic" 
      android:textColor="#ffffff" 
      android:textSize="15dp" /> 

     </LinearLayout> 

<LinearLayout 
    android:id="@+id/ll_artists_header" 
    android:layout_width="match_parent" 
    android:layout_height="90dip" 
    android:layout_marginTop="0dp" 
    android:orientation="horizontal" 
    android:weightSum="3" > 

    <LinearLayout 
     android:id="@+id/ll_artists_chart" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/chart_unselected" 
     android:layout_weight="1" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/tv_artists_chart" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="35dp" 
      android:layout_marginTop="65dp" 
      android:text="Chart" 
      android:textColor="#ffffff" 
      android:textSize="15dp" /> 
    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/ll_artists_newrelease" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/newrelease_unselected" 
     android:layout_weight="1" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/tv_artists_newrelease" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="5dp" 
      android:layout_marginTop="65dp" 
      android:text="New Releases" 
      android:textColor="#ffffff" 
      android:textSize="15dp" /> 
    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/ll_artists_artists" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:background="@drawable/artists_selected" 
     android:layout_weight="1" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/tv_artists_artists" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="30dp" 
      android:layout_marginTop="65dp" 
      android:text="Artists" 
      android:textColor="#ffffff" 
      android:textSize="15dp" /> 
    </LinearLayout> 
</LinearLayout> 

<LinearLayout 
    android:id="@+id/ll_artists_menuvotes_newrelease" 
    android:layout_width="match_parent" 
    android:layout_height="75dp" 
    android:layout_below="@+id/ll_artists_header" 
    android:background="@drawable/vote_bar" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tv_artists_menuvotes_newrelease" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_marginLeft="5dp" 
     android:text="Votes from xx-xx-xxx to xx-xx-xxx" 
     android:textColor="#ffffff" /> 

    <EditText 
     android:id="@+id/et_artists_searchWord" 
     android:layout_width="fill_parent" 
     android:layout_height="40dip" 
     android:layout_alignParentTop="true" 
     android:layout_centerVertical="true" 
     android:layout_marginLeft="7dip" 
     android:layout_marginRight="7dip" 
     android:layout_marginTop="8dip" 
     android:ems="10" 
     android:hint="Enter Word To Search" 
     android:background="@drawable/et_bar" > 

     <requestFocus /> 
    </EditText> 
</LinearLayout> 

<RelativeLayout 
    android:id="@+id/rl_artists_listview" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_below="@+id/ll_artists_menuvotes_newrelease" > 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 
    </ListView> 
    <!-- <ListView 
     android:id="@+id/lv_artists_listview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" > 
    </ListView> --> 
</RelativeLayout> 

+0

Вы не объяснили нам, в чем проблема. –

+0

@ Duncan Спасибо за ур ответ, проблема в том, что я понятия не имею о функциональности поиска, и я впервые использовал функцию поиска, поэтому, пожалуйста, дайте мне точную идею, sugession или help.Thanks alot –

+0

@FarhanShah Вы получаете -отей от меня. Похоже, вы не проводили никаких предварительных исследований, и ваш первый порт захода должен был отправить вопрос о переполнении стека. –

ответ

3

Создайте пользовательский фильтр, как это:

public static List<YourObject> filter(String string, 
     Iterable<YourObject> iterable, boolean byName) { 
    if (iterable == null) 
     return new LinkedList<YourObject>(); 
    else { 
     List<YourObject> collected = new LinkedList<YourObject>(); 
     Iterator<YourObject> iterator = iterable.iterator(); 
     if (iterator == null) 
      return collected; 
     while (iterator.hasNext()) { 
      YourObject item = iterator.next(); 
      collected.add(item); 
     } 
     return collected; 
    } 
} 

и вызова это как на addTextChangeListener из EditText

List<YourObject> list = filter(s.toString(),alproductInfoDTO, true); 
contactList.addAll(list); 

, а затем вызвать setAdapter снова.

+0

что вы хотите сделать? – Vijju

+0

@jay Я оставил бы его как есть. Вы уже дали прекрасный ответ. – rene

+0

@jay я не понял alproductInfoDTO ??? –

Смежные вопросы