Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 點擊Edittext,同時出現搜索歷史展示和系統軟鍵盤(升級版)

點擊Edittext,同時出現搜索歷史展示和系統軟鍵盤(升級版)

編輯:關於Android編程

上一篇博客,也是寫的點擊Edittext,同時出現搜索歷史展示和系統軟鍵盤,但是,有個小問題:如果有2條以上的搜索歷史,展示的時候,默認顯示前2條。這個時候,如果點擊“X”號刪除這條搜索歷史,是不行的,必須要全部展示的情況下,才能刪除選中的那一條。這篇博客,對這個bug進行了處理

源碼如下

展示搜索歷史的Listview的Item:option_item_3




    

        

        
    

    

        

        

    

    

展示搜索歷史的Listview的Adapter:OptionsAdapter_3

package com.chen.customviewdemo.adapter;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chen.customviewdemo.R;
import com.chen.customviewdemo.listener.HandleListviewItemListener;
import com.chen.customviewdemo.utils.CHEN;

import java.util.ArrayList;

/**
 * 適配器
 */
public class OptionsAdapter_3 extends BaseAdapter {
    private ArrayList list = new ArrayList();
    private Activity activity = null;

    private HandleListviewItemListener handleListviewItemListener;

    private int count = 0;

    /**
     * 自定義構造方法
     *
     * @param activity
     * @param list
     */
    public OptionsAdapter_3(Activity activity, HandleListviewItemListener listener, ArrayList list) {
        this.activity = activity;
        this.list = list;
        handleListviewItemListener = listener;
    }

    @Override
    public int getCount() {
        count = CHEN.showAllSearchHistory ? 2 : list.size();
        return count;
        //        return list.size();
    }

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

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

    class ViewHolder {
        TextView textView;
        ImageView imageView;
        TextView show_all_history;
        TextView cancel_history;
        RelativeLayout show_all_history_or_cancel;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            //下拉項布局
            convertView = LayoutInflater.from(activity).inflate(R.layout.option_item_3, null);
            holder.textView = (TextView) convertView.findViewById(R.id.item_text);
            holder.imageView = (ImageView) convertView.findViewById(R.id.delImage);
            holder.show_all_history = (TextView) convertView.findViewById(R.id.show_all_history);
            holder.cancel_history = (TextView) convertView.findViewById(R.id.cancel_history);
            holder.show_all_history_or_cancel = (RelativeLayout) convertView.findViewById(R.id.show_all_history_or_cancel);

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

        if (position == count - 1) {
            holder.show_all_history_or_cancel.setVisibility(View.VISIBLE);
            if (CHEN.showAllSearchHistory) {
                //說明有2個以上的搜索歷史記錄
                holder.show_all_history.setVisibility(View.VISIBLE);
            } else {
                holder.show_all_history.setVisibility(View.GONE);
            }
        }else{
            holder.show_all_history_or_cancel.setVisibility(View.GONE);
        }

        /**
         * 顯示全部搜索記錄
         */
        holder.show_all_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleListviewItemListener.handleListviewItem("showAllSearchHistory", -1);
            }
        });

        /**
         * 關閉搜索記錄提示
         */
        holder.cancel_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleListviewItemListener.handleListviewItem("cancelSearchHistoryTip", -1);
            }
        });

        holder.textView.setText(list.get(position));

        //為下拉框選項文字部分設置事件,最終效果是點擊將其文字填充到文本框
        holder.textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleListviewItemListener.handleListviewItem("setSelestData", position);
            }
        });

        //為下拉框選項刪除圖標部分設置事件,最終效果是點擊將該選項刪除
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleListviewItemListener.handleListviewItem("delSelestData", position);
            }
        });
        return convertView;
    }
}

Activity的布局:activity_main_10




    


    

    

    


    


Activity源碼:MainActivity_10

package com.chen.customviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.chen.customviewdemo.adapter.OptionsAdapter_3;
import com.chen.customviewdemo.listener.HandleListviewItemListener;
import com.chen.customviewdemo.utils.CHEN;
import com.chen.customviewdemo.utils.SharedPreferencesUtil;
import com.chen.customviewdemo.utils.Utils;

import java.util.ArrayList;

/**
 * 搜索歷史有2條以上時,默認顯示2條,這個時候,也可以點擊刪除
 */
public class MainActivity_10 extends Activity implements View.OnClickListener, HandleListviewItemListener {

    //下拉框選項數據源
    private ArrayList datas;
    //文本框
    private EditText et;
    //保存輸入過的數據
    private TextView save_input_data;
    //用於展示數據的
    private TextView show_pop;
    //清理數據
    private TextView clear;
    //保存搜索數據
    SharedPreferencesUtil spUtil;
    //展示搜索歷史的listview
    ListView search_history_lv;
    //適配器
    private OptionsAdapter_3 adapter;

    /**
     * 臨時存放數據的
     */
    //    private ArrayList tempDatas;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_10);

        spUtil = new SharedPreferencesUtil(MainActivity_10.this);
        datas = new ArrayList();

        search_history_lv = (ListView) findViewById(R.id.search_history_lv);
        adapter = new OptionsAdapter_3(this, this, datas);
        search_history_lv.setAdapter(adapter);

        //初始化界面組件
        et = (EditText) findViewById(R.id.edittext);

        clear = (TextView) findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datas.clear();
                spUtil.saveSearchKeyHistory("");
            }
        });

        save_input_data = (TextView) findViewById(R.id.save);
        //設置點擊事件,恢復下拉框列表數據,沒有什麼作用,純粹是為了方便多看幾次效果而設置
        save_input_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //編輯框輸入的數據
                String willSave = et.getText().toString().trim();
                if (!TextUtils.isEmpty(willSave)) {
                    String saveData = spUtil.getSearchKeyHistory();

                    if (TextUtils.isEmpty(saveData)) {
                        //說明之前沒有搜索歷史,直接存放當前的搜索數據
                        spUtil.saveSearchKeyHistory(willSave);
                    } else {
                        if (!Utils.isContainsStr(saveData, willSave)) {
                            //已有數據中,不包含新的搜索內容,把最新搜索內容加到最前面
                            saveData = willSave + "-" + saveData;
                        } else {
                            //已有數據中,包含新的搜索內容,要重新排序,把最新的搜索內容,放在最前面
                            String[] oldOrder = saveData.split("-");
                            int equaseIndex = 0;
                            for (int i = 0; i < oldOrder.length; i++) {
                                if (oldOrder[i].equals(willSave)) {
                                    equaseIndex = i;
                                    break;
                                }
                            }
                            if (equaseIndex != 0) {
                                //新的搜索內容,不在保存數據的第一條。(如果在第一條,就不用處理了)
                                saveData = oldOrder[equaseIndex];
                                for (int j = 0; j < equaseIndex; j++) {
                                    saveData = saveData + "-" + oldOrder[j];
                                }
                                for (int k = equaseIndex + 1; k < oldOrder.length; k++) {
                                    saveData = saveData + "-" + oldOrder[k];
                                }
                            }

                        }
                        //項目中,輸入框默認的一次最多輸入數據是20個字。5條數據是100字。這裡再多加點。這裡正確的處理,應該是保證只保存5條。這裡偷個懶,不在詳細寫了。
                        if (saveData.length() > 150) {
                            saveData = saveData.substring(0, 150);
                        }
                        spUtil.saveSearchKeyHistory(saveData);
                    }
                }
            }
        });

        show_pop = (TextView) findViewById(R.id.show);
        show_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSearchHistory();
            }
        });

        et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("chen", "onClick---");
                if (TextUtils.isEmpty(et.getText().toString().trim())) {
                    showSearchHistory();
                }
            }
        });

    }

    /**
     * 顯示搜索歷史
     */
    public void showSearchHistory() {

        datas.clear();
        String data = spUtil.getSearchKeyHistory();
        if (!TextUtils.isEmpty(data)) {
            if (data.contains("-")) {
                String[] dList = data.split("-");
                int length = dList.length > 5 ? 5 : dList.length;
                for (int i = 0; i < length; i++) {
                    if (!TextUtils.isEmpty(dList[i])) {
                        datas.add(dList[i]);
                    }
                }
            } else {
                datas.add(data);
            }
        }

        if (datas != null && datas.size() > 0) {
            if (datas.size() > 2) {
                CHEN.showAllSearchHistory = true;
            }else{
                CHEN.showAllSearchHistory=false;
            }
            adapter.notifyDataSetChanged();
            search_history_lv.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onClick(View v) {
    }

    @Override
    public void handleListviewItem(String flag, int index) {

        //給Edittext設置選中的內容
        if ("setSelestData".equals(flag)) {
            et.setText(datas.get(index));
            search_history_lv.setVisibility(View.GONE);

        }
        //刪除選擇條目
        if ("delSelestData".equals(flag)) {
            datas.remove(index);

            if(CHEN.showAllSearchHistory){
                //如果當前是只顯示前2條,就不用再判斷了。
                if (datas.size() > 2) {
                    CHEN.showAllSearchHistory = true;
                } else {
                    CHEN.showAllSearchHistory = false;
                }
            }

            //刷新下拉列表
            adapter.notifyDataSetChanged();

            if (datas == null || datas.size() == 0) {
                spUtil.saveSearchKeyHistory("");
            } else {
                if (datas.size() == 1) {
                    spUtil.saveSearchKeyHistory(datas.get(0));
                } else {
                    String temp = "";
                    for (int j = 0; j < datas.size(); j++) {
                        temp = temp + datas.get(j) + "-";
                    }
                    if (temp.endsWith("-")) {
                        temp = temp.substring(0, temp.length() - 1);
                    }
                    spUtil.saveSearchKeyHistory(temp);
                }
            }

        }

        //展示所有搜索歷史
        if ("showAllSearchHistory".equals(flag)) {
            CHEN.showAllSearchHistory = false;
            adapter.notifyDataSetChanged();
        }

        //關閉展示所有搜索歷史
        if ("cancelSearchHistoryTip".equals(flag)) {
            CHEN.showAllSearchHistory = false;
            search_history_lv.setVisibility(View.GONE);
        }
    }
}

用到的工具類

package com.chen.customviewdemo.utils;

import android.app.Activity;
import android.text.TextUtils;
import android.util.DisplayMetrics;

/**
 * 工具類
 */
public class Utils {

    /**
     * 判斷一個大的string裡面,是否包含另一個小的string
     *
     * @param mianStr 大的string(主string)
     * @param data    要判斷的string
     * @return true表示包含,false表示不包含
     */
    public static boolean isContainsStr(String mianStr, String data) {

        try {
            if (checkStringIsEmpty(mianStr) || checkStringIsEmpty(data)) {
                return false;
            } else {
                if (mianStr.contains("-")) {
                    boolean b = false;
                    String[] arr = mianStr.split("-");

                    for (int i = 0; i < arr.length; i++) {
                        if (data.equals(arr[i])) {
                            b = true;
                        }
                    }
                    return b;
                } else {
                    if (mianStr.equals(data)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
    }
}

全局變量

package com.chen.customviewdemo.utils;

/**
 * 用於保存全局變量值
 */
public class CHEN {
    /**
     * 有2條以上的搜索歷史記錄
     */
    public static boolean showAllSearchHistory = false;
}

保存數據

package com.chen.customviewdemo.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesUtil {
    private SharedPreferences sp;
    private Context context;

    public SharedPreferencesUtil(Context context) {
        this.context = context;
    }

    public void saveSearchKeyHistory(String value) {
        sp = context.getSharedPreferences("SaveSearchKeyHistory", Context.MODE_PRIVATE);
        sp.edit().putString("searchKeyHistory", value).apply();
    }

    public String getSearchKeyHistory() {
        sp = context.getSharedPreferences("SaveSearchKeyHistory", Context.MODE_PRIVATE);
        return sp.getString("searchKeyHistory", "");
    }

}

回調接口

package com.chen.customviewdemo.listener;

/**
 * 處理listview中某個條目的監聽接口
 */
public interface HandleListviewItemListener {

    void handleListviewItem(String flag, int index);
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved