自定义控件实现轮播图

来源:互联网 发布:淘宝宝贝拍照灯光选择 编辑:程序博客网 时间:2024/06/05 12:52

微笑微笑微笑导入image-loader依赖

微笑微笑微笑效果图


微笑微笑微笑AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.samsung.diyizhoulianxi"><uses-permission android:name="android.permission.INTERNET"></uses-permission>    <application        android:name=".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=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".Main2Activity"></activity>    </application></manifest>微笑微笑微笑layout下的activity_main布局
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout    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.samsung.diyizhoulianxi.MainActivity">   <com.samsung.diyizhoulianxi.view.Mylunbo       android:id="@+id/lunbo"       android:layout_width="wrap_content"       android:layout_height="wrap_content">   </com.samsung.diyizhoulianxi.view.Mylunbo></android.support.constraint.ConstraintLayout>
微笑微笑微笑layout下的activity_main2布局
<?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"    tools:context="com.samsung.diyizhoulianxi.Main2Activity">  <WebView      android:layout_width="match_parent"      android:layout_height="match_parent"      android:id="@+id/web"      ></WebView></LinearLayout>
微笑微笑微笑layout下的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>
微笑微笑微笑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>
微笑微笑微笑主包里view包下Myadapter类
public class Myadapter extends PagerAdapter {    private Context context;    private List<Bean> arr;    private Myjiekou myjiekou;    public Myadapter(Context context,List arr,Myjiekou 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;    }}
微笑微笑微笑主包里view包下Mylunbo类
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);    }}微笑微笑微笑主包下App类 
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);    }}
微笑微笑微笑主包下Bean类
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;    }}
微笑微笑微笑主包下Main2Activity类
public class Main2Activity 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);    }}
微笑微笑微笑主包下MainActivity类
public class MainActivity extends AppCompatActivity implements Myjiekou{   private List<Bean> arr=new ArrayList<>();    private Mylunbo viewById;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        viewById = (Mylunbo) findViewById(R.id.lunbo);        init();    }    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, Main2Activity.class);            intent.putExtra("url",bean.getUrl());            startActivity(intent);        }else{            Toast.makeText(MainActivity.this,"我要跳转到商品详情页",Toast.LENGTH_LONG).show();        }    }}
微笑微笑微笑主包下Myjiekou接口
public interface Myjiekou {    void Jiekou(int string);}


原创粉丝点击