728x90

Android Studio SearchView 기능을 이용하면 검색처리가 좀 더 편하다.


검색어 자동완성같은 기능을 구현하기 위한 방법이라고 봐도 된다.

먼저, http://abhiandroid.com/ui/searchview 게시글을 다운로드 해서 본인 PC에서 직접 테스트한다.

다운로드 하려면 성명과 E-Mail 을 입력하고 나면 Dropbox 에 올려진 파일을 다운로드 할 수 있다.


아래 내용은 서버에 있는 자료를 ArrayList 에 저장하고 저장된 자료를 기반으로 SearchView 구현에 필요한 것만 발췌한 것이다.


앱 build.gradle 설정 내용 예시




MainActivity.java 주요 내용

변수선언

    ListView listView;
    private ArrayList<Address_Item> addressItemList = new ArrayList<>(); // 서버 원본 데이터 리스트
    private ArrayList<Address_Item> searchItemList = new ArrayList<>(); // 검색한 데이터 리스트
    ListViewAdapter listViewAdapter;
    SearchView editsearch; 

 public void onCreate(Bundle savedInstanceState)

        listView = (ListView) findViewById(R.id.listview);
        listViewAdapter = new ListViewAdapter(this, searchItemList);
        listView.setAdapter(listViewAdapter); // Binds the Adapter to the ListView
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);


        // Adapter에 추가 데이터를 저장하기 위한 ArrayList
        getServerData();

        // Locate the EditText in listview_main.xml
        editsearch = (SearchView) findViewById(R.id.search);
        editsearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 문자열 입력을 완료했을 때 문자열 반환
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 문자열이 변할 때마다 바로바로 문자열 반환
                String text = newText;
                listViewAdapter.filter(text);
                return false;
            }
        });

     private void getServerData() {
        settings = getSharedPreferences("settings", Activity.MODE_PRIVATE);
        Uri.Builder builder = new Uri.Builder()
                .appendQueryParameter("idx", settings.getString("idx",""));
        String postParams = builder.build().getEncodedQuery();
        new getJSONData().execute(Value.IPADDRESS + "/get_json.php",postParams);
    }


    class getJSONData extends AsyncTask<String, Void, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("Personal Profile JSON Parse");
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();  // Show progressdialog
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                return PHPComm.getJson(params[0],params[1]);
            } catch (Exception e) {
                return new String("Exception: " + e.getMessage());
            }
        }

        protected void onPostExecute(String result){
            searchJSON=result;
            showList();
            mProgressDialog.dismiss();
        }
    }


    // 아이템 데이터 추가를 위한 메소드
    public void getServerDataList(String photo_image, String uid, String name, String mobileNO, String officeNO, boolean checkItem_flag) {
        Address_Item item = new Address_Item();
        item.setPhoto(photo_image);
        item.setIdx(uid);
        item.setUserNM(name);
        item.setMobileNO(mobileNO);
        item.setOfficeNO(officeNO);
        item.setCheckBoxState(checkItem_flag);

        addressItemList.add(item);
    }

    // 선택한 데이터 추가를 위한 메소드
    public void selectDataList(String photo_image, String uid, String name, String mobileNO, String officeNO, boolean checkItem_flag) {
        Address_Item item = new Address_Item();
        item.setPhoto(photo_image);
        item.setIdx(uid);
        item.setUserNM(name);
        item.setMobileNO(mobileNO);
        item.setOfficeNO(officeNO);
        item.setCheckBoxState(checkItem_flag);

        searchItemList.add(item);
    }

     // 서버 정보를 파싱하기 위한 변수 선언
    String searchJSON;
    private static final String TAG_RESULTS="result";
    private static final String TAG_UID = "uid"; // 서버 테이블의 실제 필드명
    private static final String TAG_NAME = "userNM";
    private static final String TAG_MobileNO ="mobileNO";
    private static final String TAG_OfficeNO ="telNO";
    private static final String TAG_Image = "photo"; // 이미지 필드
    JSONArray peoples = null;

    protected void showList() {
        try {
            JSONObject jsonObj = new JSONObject(searchJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);

            addressItemList.clear(); // 서버에서 가져온 데이터 초기화
            for(int i=0;i < peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                final String uid = c.getString(TAG_UID);
                final String name = c.getString(TAG_NAME);
                final String mobileNO = c.getString(TAG_MobileNO);
                final String officeNO = c.getString(TAG_OfficeNO);
                final String Photo_Image = c.getString(TAG_Image);

                // 서버에서 가져온 데이터 저장 (원본 보관용과 검색용 사용 목적)
                getServerDataList(Photo_Image, uid, name, mobileNO, officeNO,false);
                selectDataList(Photo_Image, uid, name, mobileNO, officeNO,false);
            }

            runOnUiThread(new Runnable() { // 화면에 반영하기 위하여 실시간 갱신한다.
                @Override
                public void run() {
                    // 갱신된 데이터 내역을 어댑터에 알려줌
                    listViewAdapter.notifyDataSetChanged();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

 ListViewAdapter 주요 부분
    private class ListViewAdapter extends BaseAdapter {
        ImageLoader imageLoader;
        Context context;
        LayoutInflater inflater;
        private List<Address_Item> lvItemList = null;

        public ListViewAdapter(Context context, List<Address_Item> items) {
            this.context = context;
            imageLoader = new ImageLoader(context);
            lvItemList = items;
        }

        public class ViewHolder {
            LinearLayout child_layout;
            ImageView photo_Image;
            TextView tv_name;
            TextView tv_mobileNO;
            TextView tv_officeNO;
            ImageView child_btn;
            CheckBox checkbox;
        }

        @Override
        public int getCount() {
            return lvItemList.size();
        }

        @Override
        public Object getItem(int position) {
            return lvItemList.get(position);
        }

        // 지정한 위치(position)에 있는 데이터 리턴
        @Override
        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            final Context context = parent.getContext();
            final Integer index = Integer.valueOf(position);

            // 화면에 표시될 View
            if(convertView == null){
                viewHolder = new ViewHolder();

                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.address_item,parent,false);

                convertView.setBackgroundColor(0x00FFFFFF);
                convertView.invalidate();

                // 화면에 표시될 View 로부터 위젯에 대한 참조 획득
                viewHolder.photo_Image = (ImageView) convertView.findViewById(R.id.profile_Image);
                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.child_name);
                viewHolder.tv_mobileNO = (TextView) convertView.findViewById(R.id.child_mobileNO);
                viewHolder.tv_officeNO = (TextView) convertView.findViewById(R.id.child_officeNO);
                viewHolder.child_btn = (ImageView) convertView.findViewById(R.id.child_Btn);
                viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.list_cell_checkbox);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            // PersonData 에서 position 에 위치한 데이터 참조 획득
            final Address_Item addressItem = lvItemList.get(position);

            if(addressItem.getPhoto().equals("")){
                final Bitmap Base_Profile = PHPComm.autoresize_decodeResource(getResources(), R.drawable.photo_base, 160);
                viewHolder.photo_Image.setImageBitmap(Base_Profile);
            } else {
                String photoURL = Value.IPADDRESS + "/photos/" + addressItem.getPhoto();
                imageLoader.DisplayImage(photoURL, viewHolder.photo_Image);
            }

            viewHolder.tv_name.setText(addressItem.getUserNM());
            viewHolder.tv_mobileNO.setText(PhoneNumberUtils.formatNumber(addressItem.getMobileNO()));
            viewHolder.tv_officeNO.setText(PhoneNumberUtils.formatNumber(addressItem.getOfficeNO()));

            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    isMSG = true;
                    relative2.setVisibility(View.VISIBLE);
                    listViewAdapter.notifyDataSetChanged();
                    return false;
                }
            });

            if (isMSG == false) {
                viewHolder.child_btn.setVisibility(View.VISIBLE);
                viewHolder.child_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        builder.show();
                    }
                });
                viewHolder.checkbox.setVisibility(View.GONE);
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(getApplicationContext(), "상세보기를 눌렀습니다 ===" + addressItem.getIdx(), Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                if (isMSG == true) {
                    viewHolder.child_btn.setVisibility(View.GONE);
                    viewHolder.checkbox.setVisibility(View.VISIBLE);
                    viewHolder.checkbox.setTag(position); // This line is important.

                    viewHolder.checkbox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(lvItemList.get(position).isCheckBoxState() == true){
                                lvItemList.get(position).setCheckBoxState(false);
                            } else {
                                lvItemList.get(position).setCheckBoxState(true);
                            }
                        }
                    });

                    convertView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(viewHolder.checkbox.isChecked() == false){
                                viewHolder.checkbox.setChecked(true);
                                lvItemList.get(position).setCheckBoxState(true);
                            } else {
                                viewHolder.checkbox.setChecked(false);
                                lvItemList.get(position).setCheckBoxState(false);
                            }
                        }
                    });

                }
            }

            // 재사용 문제 해결
            if(lvItemList.get(position).isCheckBoxState() == true){
                viewHolder.checkbox.setChecked(true);
            } else {
                viewHolder.checkbox.setChecked(false);
            }

            return convertView;
        }

        // Filter Class
        public void filter(String charText) {
            charText = charText.toLowerCase(Locale.getDefault());
            lvItemList.clear();
            if (charText.length() == 0) {
                lvItemList.addAll(addressItemList);
            } else {
                for (Address_Item wp : addressItemList) {
                    if (wp.getUserNM().toLowerCase(Locale.getDefault()).contains(charText)) {
                        lvItemList.add(wp);
                    }
                }
            }
            notifyDataSetChanged();
        }

    }


foreach 문의 기본적인 내용은 http://link2me.tistory.com/1204 참조하면 된다.

728x90
블로그 이미지

Link2Me

,