轮播+搜索历史



============================================================================

main_activity==============================================================

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_height="match_parent"
    tools:context="com.example.mo_ni.View.activity.MainActivity">

    <RelativeLayout
        android:id="@+id/relat"
        android:background="#3F51B5"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <ImageView
            android:id="@+id/tc"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginTop="10dp"
            android:layout_alignParentLeft="true"
            android:src="@drawable/leftjiantou"
            android:textSize="30sp" />
        <TextView
            android:layout_width="wrap_content"
            android:textSize="24sp"
           android:layout_centerVertical="true"
           android:layout_alignParentRight="true"
            android:layout_height="wrap_content"
            android:text="搜索"/>
    </RelativeLayout>

<com.example.mo_ni.View.activity.Mylunbo
    android:id="@+id/lunbo"
    android:layout_marginTop="50dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

</com.example.mo_ni.View.activity.Mylunbo>

</RelativeLayout>

main_actvity2===================================================================

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".View.activity.MainActvity2">
    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/web"
        ></WebView>
</LinearLayout>

main_activity3==================================================================

<?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:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".View.activity.MainActvity3">

    <com.example.mo_ni.View.activity.Mytitle
        android:id="@+id/mtl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="热搜"
        android:textSize="50dp" />
    <RelativeLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="150dp">

        <com.example.mo_ni.View.activity.XCFlowLayout
            android:id="@+id/flowlayout"
            android:layout_width="match_parent"
            android:layout_height="150dp">

        </com.example.mo_ni.View.activity.XCFlowLayout>
    </RelativeLayout>

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="历史记录"
        android:textSize="50dp" />


    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <Button
        android:id="@+id/bt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="清空历史记录"/>



</LinearLayout>

layout=====================================================================

<?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">

    <TextView
        android:id="@+id/tvv1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

lunbo======================================================================

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="200dp">

    </android.support.v4.view.ViewPager>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/ll"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="200dp"
        ></LinearLayout>
</RelativeLayout>

title=======================================================================

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

    <ImageView
        android:id="@+id/tv"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_marginTop="10dp"
        android:layout_alignParentLeft="true"
        android:src="@drawable/leftjiantou"
        android:textSize="30sp" />

    <RelativeLayout
        android:id="@+id/rl"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/tvv"
        android:layout_marginRight="50dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">

        <EditText
            android:id="@+id/et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:textSize="20sp" />

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="270dp"
            android:src="@drawable/root" />

    </RelativeLayout>


    <TextView
        android:id="@+id/tvv"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="搜索"
        android:textSize="22sp" />
</RelativeLayout>

drawable-dot_focuable======================================================

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

</shape>

drawable-dot_normal==============================================================

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <stroke
        android:width="2dp"
        android:color="#ff0000" />
    <corners android:radius="360dip" />

</shape>

shape=======================================================================

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#666666" />
    <corners android:radius="10dp" />
    <padding
        android:left="5dp"
        android:right="5dp"
        android:top="5dp"
        android:bottom="5dp"
        />
</shape >

Bean================================================================

package com.example.mo_ni.Modle.bean;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class Bean {
    private String icon;
    private String url;
    private int type;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public Bean(String icon,String url,int type){
        this.icon=icon;
        this.url=url;
        this.type=type;
    }
}

MainActivity======================================================

package com.example.mo_ni.View.activity;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.mo_ni.Modle.bean.Bean;
import com.example.mo_ni.R;
import com.example.mo_ni.View.adapter.Myadapter;
import com.example.mo_ni.View.fragment.Myjiekou;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements Myjiekou, View.OnClickListener {

    private List<Bean> arr=new ArrayList<>();
    private Mylunbo viewById;
    private RelativeLayout Relat;
    private ImageView tc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewById = (Mylunbo) findViewById(R.id.lunbo);
        Relat =(RelativeLayout) findViewById(R.id.relat);
        tc = (ImageView) findViewById(R.id.tc);
        Relat.setOnClickListener(this);
        init();
        tc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                        }
                    }
                }.start();
            }
        });

    }
    @SuppressLint("StaticFieldLeak")
    private void init() {
        new AsyncTask<String,Void,String>(){
            @Override
            protected String doInBackground(String... strings) {
                StringBuffer sb=new StringBuffer();
                String str=new String();
                String string = strings[0];
                try {
                    URL url = new URL(string);
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    while ((str=bufferedReader.readLine())!=null){
                        sb.append(str);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return sb.toString();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    JSONArray data = jsonObject.optJSONArray("data");
                    for(int i=0;i<data.length();i++){
                        JSONObject jsonObject1 = data.optJSONObject(i);
                        arr.add(new Bean(jsonObject1.optString("icon"),jsonObject1.optString("url"),jsonObject1.optInt("type"))) ;
                    }
                    viewById.setAdapter(new Myadapter(MainActivity.this,arr,MainActivity.this));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute("http://120.27.23.105/ad/getAd");
    }


    @Override
    public void Jiekou(int string) {
        Bean bean = arr.get(string);
        if(bean.getType()==0){
            Intent intent = new Intent(MainActivity.this, MainActvity2.class);
            intent.putExtra("url",bean.getUrl());
            startActivity(intent);
        }else{
            Toast.makeText(MainActivity.this,"我要跳转到商品详情页",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent2 = new Intent(MainActivity.this, MainActvity3.class);
        startActivity(intent2);
    }
}

MainActvity2==================================================================

package com.example.mo_ni.View.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.example.mo_ni.R;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class MainActvity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Intent intent = getIntent();
        String dz = intent.getStringExtra("url");

        WebView webView = (WebView) findViewById(R.id.web);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setJavaScriptEnabled(true);
        webView.loadUrl(dz);

    }
}

MainActivity3==================================================================

package com.example.mo_ni.View.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mo_ni.R;

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

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class MainActvity3 extends AppCompatActivity {

    private String mNames[] = {
            "VIVO", "OPPO", "LG",
            "华为", "苹果", "锤子",
            "HP", "华硕", "联想",
            "小米", "金立", "海尔",
            "乐视", "黑米", "雷神", "外星人"
    };

    private XCFlowLayout mFlowLayout;
    private ListView lv;
    private Mytitle mtl;
    private Button bt;
    private List<String> list = new ArrayList<String>();

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

        mFlowLayout = (XCFlowLayout) findViewById(R.id.flowlayout);
        lv = (ListView) findViewById(R.id.lv);
        mtl = (Mytitle) findViewById(R.id.mtl);
        bt = (Button) findViewById(R.id.bt);

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();
                lv.setAdapter(new myBaseAdapter());


            }
        });
        initChildViews();


        jilu();
    }

    private void initChildViews() {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 5;
        lp.rightMargin = 5;
        lp.topMargin = 5;
        lp.bottomMargin = 5;
        for (int i = 0; i < mNames.length; i++) {
            TextView view = new TextView(this);
            view.setText(mNames[i]);
            view.setTextColor(Color.WHITE);
            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape));
            mFlowLayout.addView(view, lp);
            final int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    list.add(mNames[finalI]);
                    lv.setAdapter(new myBaseAdapter());


                }
            });


        }

    }

    private void jilu() {
        mtl.setJiekou(new Mytitle.onsetHuida() {
            @Override
            public void huida(String aa) {
                Toast.makeText(MainActvity3.this, aa + "", Toast.LENGTH_SHORT).show();
                list.add(aa);
                lv.setAdapter(new myBaseAdapter());
            }


        });


        lv.setAdapter(new myBaseAdapter());


    }

    class myBaseAdapter extends BaseAdapter {


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


        @Override
        public Object getItem(int position) {
            return null;
        }


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


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHold hold = null;
            if (convertView == null) {
                if (hold == null) {
                    hold = new ViewHold();
                    convertView = View.inflate(MainActvity3.this, R.layout.layout, null);
                    hold.tv = convertView.findViewById(R.id.tvv1);
                }
                convertView.setTag(hold);
            } else {


                hold = (ViewHold) convertView.getTag();
            }


            hold.tv.setText(list.get(position));


            return convertView;
        }
    }

    class ViewHold {
        TextView tv;
    }
}

App========================================================================

package com.example.mo_ni.View.activity;

import android.app.Application;

import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(this)
                .memoryCacheExtraOptions(480, 800) // max width, max height,即保存的每个缓存文件的最大长宽
                .threadPoolSize(5)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(new BaseImageDownloader(this, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
                .writeDebugLogs() // Remove for release app
                .build();//开始构建
//初始化imageloader;
        ImageLoader.getInstance().init(config);

    }
}

MyLunbo=====================================================================

package com.example.mo_ni.View.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.mo_ni.R;
import com.example.mo_ni.View.adapter.Myadapter;

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

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class Mylunbo extends LinearLayout {

    private LinearLayout ll;
    private ImageView imageView;
    private List<ImageView> image=new ArrayList<>();
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentItem = pager.getCurrentItem();
            pager.setCurrentItem(currentItem+1);
            handler.sendEmptyMessageDelayed(0,5000);
        }
    };
    private ViewPager pager;
    private View view;

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

    public Mylunbo(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public Mylunbo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        view = View.inflate(getContext(), R.layout.lunbo, this);
        pager = view.findViewById(R.id.pager);
        jiadian();
        handler.sendEmptyMessage(5000);
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i=0;i<image.size();i++)
                {
                    if(i==position%image.size())
                    {
                        image.get(i).setImageResource(R.drawable.dot_focuable);//修改图片颜色
                    }else
                    {
                        image.get(i).setImageResource(R.drawable.dot_normal);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    public void jiadian() {
        Log.e("aaa","aaa");
        //得到LinearLayout布局
        ll = (LinearLayout) view.findViewById(R.id.ll);
        image.clear();//清空图片集合
        ll.removeAllViews();//清空LinearLayout布局
        for (int i=0;i<4;i++)//添加
        {
            //创建一个图片布局
            imageView = new ImageView(getContext());
            if(i==0)
            {
                imageView.setImageResource(R.drawable.dot_focuable);
            }else
            {
                imageView.setImageResource(R.drawable.dot_normal);
            }
            LayoutParams layoutParams = new LayoutParams(20, 20);//圆点大小
            image.add(imageView);//圆点添加到图片集合中
            ll.addView(imageView,layoutParams);//圆点添加到LinearLayout中
        }
    }


    public void setAdapter(Myadapter myadapter) {
        pager.setAdapter(myadapter);
    }
}

Mytitle======================================================================

package com.example.mo_ni.View.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.mo_ni.R;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class Mytitle extends RelativeLayout {

    private onsetHuida onsethuida;
    private EditText et;
    private TextView tvv;
    private ImageView tv;


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


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


    public Mytitle( Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater from = LayoutInflater.from(context);
        View inflate = from.inflate(R.layout.title, this, true);

        tvv = inflate.findViewById(R.id.tvv);

        tv = inflate.findViewById(R.id.tv);


        et = (EditText) inflate.findViewById(R.id.et);


        tvv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onsethuida.huida(et.getText().toString());
            }
        });

        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                        }
                    }
                }.start();
            }

        });
    }




    public interface onsetHuida{
        void huida(String aa);


    }


    public void setJiekou(onsetHuida onsethuida){
        this.onsethuida=onsethuida;
    }
}

XCFlowLayout==================================================================

package com.example.mo_ni.View.activity;

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

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

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

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


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


    public XCFlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs,0);
    }


    public XCFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub


        //父控件传进来的宽度和高度以及对应的测量模式
        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) 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);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }





    @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) {
        // TODO Auto-generated method stub


        return new MarginLayoutParams(getContext(), attrs);
    }
}

MyAdapter====================================================================

package com.example.mo_ni.View.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.mo_ni.Modle.bean.Bean;
import com.example.mo_ni.View.activity.MainActivity;
import com.example.mo_ni.View.fragment.Myjiekou;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public class Myadapter extends PagerAdapter {
    private Context context;
    private List<Bean> arr;
    private Myjiekou myjiekou;

    public Myadapter(Context context, List arr, MainActivity myjiekou){
        this.context=context;
        this.arr=arr;
        this.myjiekou=myjiekou;
    }
    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageLoader.getInstance().displayImage(arr.get(position%arr.size()).getIcon(),imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myjiekou.Jiekou(position%arr.size());
            }
        });
        container.addView(imageView);
        return imageView;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return  Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }
}

Myjiekou接口=================================================================

package com.example.mo_ni.View.fragment;

/**
 * Created by 你家大林哥 on 2018/5/12.
 */

public interface Myjiekou {
    void Jiekou(int string);
}

权限================================================================

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mo_ni">
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:name=".View.activity.App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".View.activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".View.activity.MainActvity2"/>
        <activity android:name=".View.activity.MainActvity3"/>
    </application>

</manifest>

依赖==================================================================

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

猜你喜欢

转载自blog.csdn.net/nijiadalinge/article/details/80301698