Android 带搜索历史的搜索

先上效果图

 

 搜索页所用到的xml文件

   这个是搜索的

SearchActivity

的xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    >
    <RelativeLayout
        android:paddingStart="20dp"
        android:layout_marginTop="15dp"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="30dp"
        android:background="@drawable/edittext_garden"
        android:layout_width="match_parent"
        android:layout_height="40dp">
        <ImageView
            android:id="@+id/qu"
            android:layout_centerVertical="true"
            android:src="@drawable/search"
            android:layout_width="20dp"
            android:layout_height="20dp">

        </ImageView>
        <EditText
            android:singleLine="true"
            android:maxLines="1"
            android:imeOptions="actionSearch"
            android:layout_marginEnd="15dp"
            android:layout_toStartOf="@+id/shanchu"
            android:layout_marginStart="25dp"
            android:layout_toEndOf="@+id/qu"
            android:id="@+id/edittext_search"
            android:background="@null"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </EditText>
        <ImageView
            android:layout_marginEnd="15dp"
            android:id="@+id/shanchu"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:src="@drawable/shanchuan"
            android:layout_width="20dp"
            android:layout_height="20dp">

        </ImageView>

    </RelativeLayout>
    <com.ziytek.mysearchview.ZFlowLayout
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        android:layout_marginTop="15dp"
        android:id="@+id/zflow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.ziytek.mysearchview.ZFlowLayout>
</LinearLayout>

 这个是下面搜索历史用到的xml

 

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_content"
    android:textColor="#ffffff"
    android:paddingStart="7dp"
    android:paddingEnd="7dp"
    android:paddingTop="3dp"
    android:paddingBottom="2dp"
    android:background="@drawable/text_garden_grey"
    android:layout_marginStart="10dp"
    android:text=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</TextView>

 相关背景设置  第二个没用。。

 

 

下面是edittext_garden.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    android:shape="rectangle">
    <solid android:color="#EEEEEE"/>

    <corners android:radius="15dp" />
</shape>

下面是text_garden_grey.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    android:shape="rectangle">
    <solid android:color="#BDBDBD"/>

    <corners android:radius="3dp" />
</shape>

两张图片

 

下面上主要代码

搜索历史

ZFlowLayout

的代码块


import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class ZFlowLayout extends ViewGroup {
    /**
     * 存储所有子View
     */
    private List<List<View>> mAllChildViews = new ArrayList<>();
    /**
     * 每一行的高度
     */
    private List<Integer> mLineHeight = new ArrayList<>();

    public ZFlowLayout(Context context) {
        this(context, null);
    }

    public ZFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZFlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        //如果当前ViewGroup的宽高为wrap_content的情况
        //自己测量的宽度
        int width = 0;
        //自己测量的高度
        int height = 0;
        //记录每一行的宽度和高度
        int lineWidth = 0;
        int lineHeight = 0;

        //获取子view的个数
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            //测量子View的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            //得到LayoutParams
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            //子View占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            //子View占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
            //换行时候
            if (lineWidth + childWidth > sizeWidth) {
                //对比得到最大的宽度
                width = Math.max(width, lineWidth);
                //重置lineWidth
                lineWidth = childWidth;
                //记录行高
                height += lineHeight;
                lineHeight = childHeight;
            } else {//不换行情况
                //叠加行宽
                lineWidth += childWidth;
                //得到最大行高
                lineHeight = Math.max(lineHeight, childHeight);
            }
            //处理最后一个子View的情况
            if (i == childCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }
        //wrap_content
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllChildViews.clear();
        mLineHeight.clear();
        //获取当前ViewGroup的宽度
        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        //记录当前行的view
        List<View> lineViews = new ArrayList<View>();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            //如果需要换行
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
                //记录LineHeight
                mLineHeight.add(lineHeight);
                //记录当前行的Views
                mAllChildViews.add(lineViews);
                //重置行的宽高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                //重置view的集合
                lineViews = new ArrayList();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        //处理最后一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);

        //设置子View的位置
        int left = 0;
        int top = 0;
        //获取行数
        int lineCount = mAllChildViews.size();
        for (int i = 0; i < lineCount; i++) {
            //当前行的views和高度
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                //判断是否显示
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
                //进行子View进行布局
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
        }
    }

    /**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }
}

 

下面是搜索的Activity  

SearchActivity

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public class SearchActivity extends Activity {
    private TextView title;
    private ImageView shanchu;
    private EditText edittext_search;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        shanchu=findViewById(R.id.shanchu);
        edittext_search=findViewById(R.id.edittext_search);
        shanchu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittext_search.setText("");
            }
        });
        edittext_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    String query =edittext_search.getText().toString();
                    if(!"".equals(query)){
                        setser(query);
                    }
                    Intent i = new Intent();
                    i.putExtra("name", query);
                    setResult(1, i);
                    finish();
                    return true;
                }
                return false;
            }
        });
//        searchView=findViewById(R.id.view_search);
        title=findViewById(R.id.title);
        String ti=getIntent().getStringExtra("title");
        if(ti!=null){
            title.setText(ti);
        }
        edittext_search.setFocusable(true);
        edittext_search.setFocusableInTouchMode(true);
        edittext_search.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        list=getser();
        historyFl=findViewById(R.id.zflow);
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 10, 10, 10);
        for(int j=0;j<list.size();j++){
            View paramItemView = getLayoutInflater().inflate(R.layout.type_multiple, null);
            TextView keyWordTv = paramItemView.findViewById(R.id.tv_content);
            keyWordTv.setText(list.get(j));
            historyFl.addView(paramItemView, layoutParams);
            keyWordTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    edittext_search.setText(keyWordTv.getText().toString());
                    edittext_search.setSelection(keyWordTv.getText().toString().length());
                }
            });
        }

    }
    private ZFlowLayout historyFl;
    private List<String> list =new ArrayList<>();
    private List<String> getser(){
        String s = get(SearchActivity.this,"srarch");
        if("".equals(s)){
            list=new ArrayList<>();
        }else{
            String[] arr =  s.split(",");
            list =Arrays.asList(arr);
        }
        return list;
    }
    private void setser(String ser){
        String s = get(SearchActivity.this,"srarch");
        if("".equals(s)){
            setkevl(SearchActivity.this,"srarch",ser);
        }else{
            String[] arr =  s.split(",");
            list =Arrays.asList(arr);
            List<String> list1 =new ArrayList<>(list);
            Collections.reverse(list1);
            boolean size=false;
            for(int z=0;z<list1.size();z++){
                if(ser.equals(list1.get(z))){
                    list1.remove(z);
                    size=true;
                    break;
                }
            }
            if(list1.size()<20){
                list1.add(ser);
            }else{
                if(!size){
                    list1.remove(0);
                }
                list1.add(ser);
            }
            Collections.reverse(list1);
            StringBuffer stringBuffer =new StringBuffer();
            for(int i=0;i<list1.size();i++){
                if(i==0){
                    stringBuffer.append(list1.get(i));
                }else {
                    stringBuffer.append(",");
                    stringBuffer.append(list1.get(i));
                }
            }
            setkevl(SearchActivity.this,"srarch",stringBuffer.toString());
        }

    }


    public String get(Context context, String text){
        SharedPreferences sharedPreferences= context.getSharedPreferences("searchview", Context .MODE_PRIVATE);
        String token=sharedPreferences.getString(text,"");
        if(token==null){
            token="";
        }
        return token;
    }

    public void setkevl(Context context,String key,String value){
        SharedPreferences sharedPreferences= context.getSharedPreferences("searchview",Context.MODE_PRIVATE);
        //步骤2: 实例化SharedPreferences.Editor对象
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //步骤3:将获取过来的值放入文件
        editor.putString(key, value);
        editor.commit();
    }

}

 

在其他Activity调用的时候可以这样写

    startActivityForResult(new Intent(this,SearchActivity.class),1);
    //调用启动
    

    //下面是返回值
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1&&resultCode == 1){
            String name = data.getStringExtra("name");//搜索返回内容
            Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值