2015-07-05 3 views
2

У меня есть EditText, где пользователь может ввести любой текст, который они хотят (например, «A» или «B» или «C») из массива строк (arr [] = «A», «B», «C «). У меня есть ListView, где я хочу, чтобы результаты отображались, когда пользователь нажимает кнопку «done» на клавиатуре? Как это сделать в моем коде?Android - Как реализовать функцию поиска и вернуть результаты в ListView?

вот скриншот: enter image description here

Вот мой код?

package com.mobilecomp.add.ssproj1; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 


public class MainActivity extends ActionBarActivity { 

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


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 



package com.mobilecomp.add.ssproj1; 

import android.support.v4.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 


/** 
* A placeholder fragment containing a simple view. 
*/ 
public class MainActivityFragment extends Fragment { 

    public MainActivityFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_main, container, false); 
    } 
} 

activity_main.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/fragment" 
    android:name="com.mobilecomp.add.ssproj1.MainActivityFragment" 
    tools:layout="@layout/fragment_main" android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

fragment_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" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivityFragment"> 

    <EditText 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/inputText" 
     android:layout_centerHorizontal="true" 
     android:inputType="text" /> 

    <ListView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/searchResult" 
     android:layout_below="@+id/inputText" 
     android:layout_centerHorizontal="true" /> 

</RelativeLayout> 
+0

ch должен быть сделан? При нажатии кнопки? –

+0

я не проверил, но я нашел две ссылки: http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/ Http: // StackOverflow .com/questions/20355177/how-to-add-search-functional-in-listview – krystian71115

+0

когда нажата кнопка нажата –

ответ

0

Сначала добавьте некоторые Button к вашему fragment_main с android:[email protected]+id/button. Тогда в вашем фрагменте:

private ListView mListView; 
private EditText mEditText; 
private Button mButton; 
private ArrayList<String> mData = new ArrayList<>(); 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment_main, container, false); 

    mListView = (ListView) v.findViewById(R.id.searchResult); 
    mEditText = (EditText) v.findViewById(R.id.inputText); 
    mButton = (Button) v.findViewById(R.id.button); 
    final ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_dropdown_item_1line); 
    mListView.setAdapter(mAdapter); 

    //Some random data... 
    mData.add("A"); 
    mData.add("B"); 
    mData.add("C"); 

    //Trigger, set listener on sth... button example 
    mButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      final String fromEditText = mEditText.getText().toString().trim(); 
      for (String aaa : mData) { 
       if (aaa.contains(fromEditText)) { 
        mAdapter.add(aaa); 
       } 
      } 
     } 
    }); 
    return v; 
} 

Edit:

Вместо установки слушателя mButton, вы можете сделать:

mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
     @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      if (actionId == EditorInfo.IME_ACTION_DONE 
        || event.getAction() == KeyEvent.FLAG_EDITOR_ACTION) { 
       final String fromEditText = mEditText.getText().toString().trim(); 
       for (String aaa : mData) { 
        if (aaa.contains(fromEditText)) { 
         mAdapter.add(aaa); 
        } 
       } 
      } 
      return true; 
     } 
    }); 
+0

спасибо N1to. Интересно, можно ли это сделать без создания дополнительной кнопки? Я просто хочу, чтобы пользователь нажал «сделать» с помощью клавиатуры –

+0

ОК, проверьте мое отредактированное сообщение. –

1

Я думаю, что лучший вариант использовать TextWatcher

editText.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 

       // TODO Auto-generated method stub 
      } 

      @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 
      } 
     }); 
Смежные вопросы