初学Android之Tablayout+Fragment+ImageLoader(低仿知乎)

所需要的包已上传


接下来就是代码了 


先写adapter的


public class MyAdapter extends BaseAdapter{
    private int TEXT_ONLY = 0;
    private int IMAGE_TEXT = 1;
    Context context;
    List<DataDataBean.ResultsBean> list;
    public MyAdapter(Context context, List<DataDataBean.ResultsBean> list) {
        this.context=context;
        this.list=list;
    }

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

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

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

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getImages() != null){
            return IMAGE_TEXT;
        }

        return TEXT_ONLY;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (getItemViewType(i) == TEXT_ONLY){
            TextHolder holder;
            if (view == null){
                view = View.inflate(context, R.layout.item_text_layout,null);
                holder = new TextHolder();

                holder.textView = view.findViewById(R.id.text_title);

                view.setTag(holder);

            }else {
                holder = (TextHolder) view.getTag();
            }

            holder.textView.setText(list.get(i).getDesc());

        }else if (getItemViewType(i)==IMAGE_TEXT){

            ImageHolder holder;
            if (view == null){
                view = View.inflate(context, R.layout.item_image_layout,null);
                holder = new ImageHolder();

                holder.textView = view.findViewById(R.id.tv);
                holder.imageView = view.findViewById(R.id.iv);

                view.setTag(holder);

            }else {
                holder = (ImageHolder) view.getTag();
            }

            holder.textView.setText(list.get(i).getDesc());
            //图片
            Log.i("----",list.get(i).getImages().get(0)+"?imageView2/0/w/100");
            ImageLoader.getInstance().displayImage(list.get(i).getImages().get(0)+"?imageView2/0/w/100",holder.imageView, ImageLoaderUtil.getRoundOption());
        }

        return view;
    }
    private class TextHolder{
        TextView textView;
    }

    private class ImageHolder{
        TextView textView;
        ImageView imageView;
    }
}


然后就是application了

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        //在应用创建的时候,,,imageLoader进行全局配置
        ImageLoaderUtil.init(this);//写一个工具类对imageLoader进行初始化...应用也可以作为上下文
    }
}



bean就不写了


fragment包


依次按照图片上的顺序写

public class FragmentDongTai extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dongtai_layout,container,false);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}
发现里的和上面差不多 不写了


之后是home


public class FragmentHome extends Fragment {
    private TabLayout tabLayout;
    private ViewPager vp;
    private List<String> list;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_layout,container,false);

        tabLayout = view.findViewById(R.id.tab);
        vp = view.findViewById(R.id.vp);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list = new ArrayList<>();
        list.add("动态");
        list.add("热门");
        list.add("发现");
        vp.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public CharSequence getPageTitle(int position) {
                return list.get(position);
            }

            @Override
            public Fragment getItem(int position) {

                Fragment fragment=null;
                switch (position)
                {
                    case 0:
                        fragment=new FragmentDongTai();
                        break;
                    case 1:
                        fragment=new FragmentRemen();
                        break;
                    case 2:
                        fragment=new FragmentFaxian();
                        break;

                    default:
                        break;
                }
                return fragment;
            }

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


这个是热门


public class FragmentRemen extends Fragment implements XListView.IXListViewListener {
    private XListView xlv;
    private int page_num = 1;
    private MyAdapter myAdapter;
    private List<DataDataBean.ResultsBean> list = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_remen_layout,container,false);

        xlv = view.findViewById(R.id.xlv);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        xlv.setPullLoadEnable(true);
        xlv.setPullLoadEnable(true);
        xlv.setXListViewListener(this);


        getDataFromNet();
    }

    private void getDataFromNet() {
        NetDataUtil.getData(getActivity(), "http://gank.io/api/data/Android/10/"+page_num, new JsonStringCallaBack() {
            @Override
            public void getJsonString(String json) {
                Gson gson = new Gson();

                DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class);

                list.addAll(dataDataBean.getResults());


                setAdapter();



                xlv.stopLoadMore();
            }
        });
    }

    private void setAdapter() {
        if(myAdapter == null){
            myAdapter = new MyAdapter(getActivity(), list);
            xlv.setAdapter(myAdapter);
        }else {
            myAdapter.notifyDataSetChanged();;
        }
    }


    @Override
    public void onRefresh() {
        getDataRefresh();
    }

    private void getDataRefresh() {

        NetDataUtil.getData(getActivity(), "http://gank.io/api/data/Android/10/1", new JsonStringCallaBack() {
            @Override
            public void getJsonString(String json) {

                Gson gson = new Gson();

                DataDataBean dataDataBean = gson.fromJson(json, DataDataBean.class);

                list.clear();

                list.addAll(0,dataDataBean.getResults());


               setAdapter();


                xlv.stopRefresh();

                String format = new SimpleDateFormat("HH:mm").format(new Date(System.currentTimeMillis()));
                xlv.setRefreshTime(format);
            }
        });
    }


    @Override
    public void onLoadMore() {
        page_num ++;
        getDataFromNet();
    }
}

然后是inter包


public class FragmentXiangFa extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_xiangfa_layout,container,false);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
}


util包的 imageloaderutil

public class ImageLoaderUtil {

    /**
     * imageLoader进行配置的方法
     * @param context 上下文
     */
    public static void init(Context context) {

        //File cacheDir = StorageUtils.getCacheDirectory(context);  //指定默认的硬盘(sd)的缓存文件夹路径

        /**
         * 可以自己创建一个sd下面的文件夹作为硬盘缓存的路径
         */
        File file = new File(Environment.getExternalStorageDirectory(),"image");
        if (! file.exists()){
            file.mkdirs();
        }

        //1.创建一个ImageLoaderConfiguration,,,图片加载器的配置对象
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)

                .threadPoolSize(3) // default  线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()

                //1 TB = 1024GB 1G=1024MB 1M = 1024KB 1KB = 1024BYTE
                //LruMemoryCache,,lru最近最少使用算法...内部维护的是LinkedHashMap,,当一张图片最近很少使用的时候会从mao集合里面移除
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //指定内存缓存的大小,,2M,,可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                .memoryCacheSizePercentage(13) // default

                //指定硬盘/磁盘缓存的路径
                .diskCache(new UnlimitedDiskCache(file)) // default 可以自定义缓存路径
                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd(本地)缓存的最大值
                .diskCacheFileCount(100)  // 可以缓存的文件数量


                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs() // 打印debug log
                .build(); //开始构建

        //2.对上面配置对象的初始化
        ImageLoader.getInstance().init(config);

    }

    /**
     * 默认的展示图片的选项
     *
     * @return
     */
    public static DisplayImageOptions getDefaultOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片

                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位

                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

                .considerExifParams(true) // default


                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型

                .displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)

                .build();

        return options;
    }

    /**
     * 展示圆角的选项
     * @return
     */
    public static DisplayImageOptions getRoundOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片

                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位

                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

                .considerExifParams(true) // default


                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型

                .displayer(new RoundedBitmapDisplayer(20)) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)

                .build();

        return options;
    }

    /**
     * 展示圆形的选项
     * @return
     */
    public static DisplayImageOptions getCircleOption() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片

                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位

                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

                .considerExifParams(true) // default


                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型

                .displayer(new CircleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)

                .build();

        return options;
    }
}





public class NetDataUtil {

    /**
     * 获取数据之前先判断网络状态
     * @param path
     * @param callaBack
     */
    public static void getData(Context context,final String path, final JsonStringCallaBack callaBack) {
        if (NetWorkUtil.isConn(context)){
            Toast.makeText(context,"网络可用",Toast.LENGTH_SHORT).show();

            AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... voids) {
                    try {
                        URL url = new URL(path);

                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                        connection.setRequestMethod("GET");
                        connection.setReadTimeout(5000);
                        connection.setConnectTimeout(5000);

                        int responseCode = connection.getResponseCode();
                        if (responseCode == 200){
                            InputStream inputStream = connection.getInputStream();

                            String json = streamToString(inputStream,"utf-8");

                            return json;
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(String json) {
                    //异步拿回这个json,交给具体解析的那个类
                    callaBack.getJsonString(json);
                }
            };

            asyncTask.execute();
        }else {
            NetWorkUtil.showNoNetWorkDlg(context);
        }


    }


    private static String streamToString(InputStream inputStream, String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s = null;
            StringBuilder builder = new StringBuilder();
            while ((s = bufferedReader.readLine()) != null){
                builder.append(s);
            }

            bufferedReader.close();
            return builder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return  null;
    }
}



public class NetWorkUtil {

    /**
     * 这个方法是判断网络状态是否可用的
     * @param context
     * @return
     */
    public static boolean isConn(Context context){
        boolean bisConnFlag=false;
        //1.获取网络连接的管理对象
        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //2.通过管理者对象拿到网络的信息
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if(network!=null){
            //3.网络状态是否可用的返回值
            bisConnFlag=network.isAvailable();
        }
        return bisConnFlag;
    }

    /**
     * 如果没有网络 弹出dialog对话框,,,是否进入设置网络的页面
     * @param context
     */
    public static void showNoNetWorkDlg(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(R.mipmap.ic_launcher)         //
                .setTitle("警告")            //
                .setMessage("当前无网络,是否去设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 跳转到系统的网络设置界面
                Intent intent = null;
                // 先判断当前系统版本
                if(android.os.Build.VERSION.SDK_INT > 10){  // 3.0以上
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{
                    intent = new Intent();
                    intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
                }
                context.startActivity(intent);

            }
        }).setNegativeButton("取消", null).show();
    }
}



public class MainActivity extends AppCompatActivity {

    private RadioGroup rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg = (RadioGroup) findViewById(R.id.radio_group);
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentHome()).commit();

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                 switch (i)
                 {
                     case R.id.radio_01:
                         getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentHome()).commit();
                         break;
                     case R.id.radio_02:
                         getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentXiangFa()).commit();
                         break;
                     case R.id.radio_03:
                         getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentMarket()).commit();
                         break;
                     case R.id.radio_04:
                         getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentNotify()).commit();
                         break;
                     case R.id.radio_05:
                         getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,new FragmentMore()).commit();
                         break;
                     default:
                         break;
                 }
            }
        });
    }
}



selector里的


<item android:state_checked="true" android:drawable="@color/colorAccent"/>
<item android:state_checked="false" android:drawable="@color/colorPrimary"/>
<item android:drawable="@color/colorPrimary"/>


布局 mainactivity

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

    <FrameLayout
        android:layout_above="@+id/radio_group"
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="40dp">

    <RadioButton
        android:id="@+id/radio_01"
        android:padding="10dp"
        android:button="@null"
        android:gravity="center"
        android:background="@drawable/radio_selector"

        android:checked="true"
        android:text="首页"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <RadioButton
        android:id="@+id/radio_02"
        android:padding="10dp"
        android:button="@null"
        android:gravity="center"
        android:background="@drawable/radio_selector"
        android:text="想法"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <RadioButton
        android:id="@+id/radio_03"
        android:padding="10dp"
        android:button="@null"
        android:gravity="center"
        android:background="@drawable/radio_selector"
        android:text="市场"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <RadioButton
        android:id="@+id/radio_04"
        android:padding="10dp"
        android:button="@null"
        android:gravity="center"
        android:background="@drawable/radio_selector"
        android:text="通知"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />
    <RadioButton
        android:id="@+id/radio_05"
        android:padding="10dp"
        android:button="@null"
        android:gravity="center"
        android:background="@drawable/radio_selector"
        android:text="更多"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent" />

</RadioGroup>
</RelativeLayout>


home

<?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"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <EditText
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="羞羞的铁拳"
        />
    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        app:tabGravity="center"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@color/colorPrimaryDark"
        app:tabTextColor="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="40dp">

    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v4.view.ViewPager>

</LinearLayout>

别的layout举个例子吧


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="#123456"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>


热门

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

    <com.bawei.administrator.lianxi_1016ev.view.XListView
        android:id="@+id/xlv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></com.bawei.administrator.lianxi_1016ev.view.XListView>

</LinearLayout>



有图有文字的布局

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

    <TextView
        android:id="@+id/tv"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="100dp"
        android:layout_height="100dp" />

</LinearLayout>

只有文字的


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

之后就结束了  还差几个权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值