DrawerLayout侧滑+Image-Loader+XListView+上拉下拉 Y

main_activity

<?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"
tools:context="animtest.com.example.e531.yuekao_test_demo.MainActivity">

<android.support.v4.widget.DrawerLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mydrawer">

    <!--主内容区域-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RadioGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:id="@+id/rel_navigate"
            android:layout_alignParentBottom="true">
            <RadioButton
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="首页"
                android:button="@null"
                android:gravity="center"
                android:id="@+id/rb_index"
                android:padding="3dp"
                android:background="@drawable/rb_selector"
                android:checked="true"/>
            <RadioButton
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="视频"
                android:button="@null"
                android:padding="3dp"
                android:gravity="center"
                android:id="@+id/rb_video"
                android:background="@drawable/rb_selector"/>
            <RadioButton
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="微头条"
                android:button="@null"
                android:gravity="center"
                android:padding="3dp"
                android:id="@+id/rb_top"
                android:background="@drawable/rb_selector"/>
            <RadioButton
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="我的"
                android:padding="3dp"
                android:button="@null"
                android:gravity="center"
                android:id="@+id/rb_me"
                android:background="@drawable/rb_selector"/>

        </RadioGroup>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/rel_navigate"
            android:id="@+id/main_content"></FrameLayout>


    </RelativeLayout>

    <RelativeLayout
        android:layout_width="260dp"
        android:layout_height="match_parent"
        android:id="@+id/rel_menu"
        android:layout_gravity="start"
        android:background="#550000ff">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"
            android:id="@+id/img_title"
            android:layout_marginBottom="50dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="这是侧边栏"
            android:layout_below="@+id/img_title"/>
    </RelativeLayout>


</android.support.v4.widget.DrawerLayout>

</RelativeLayout>


content_layout

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

<animtest.com.example.e531.yuekao_test_demo.view.XListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/xlv">
</animtest.com.example.e531.yuekao_test_demo.view.XListView>
</LinearLayout>


index_layout

<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    app:tabGravity="center"
    app:tabIndicatorColor="@color/colorAccent"
    app:tabMode="scrollable"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    app:tabTextColor="@color/colorPrimary"
    android:id="@+id/mytab"></android.support.design.widget.TabLayout>

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

</LinearLayout>


me_layout

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

<TextView
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:id="@+id/tv"
    	android:text="这是我页面"
    	android:textColor="#f00"/>

</LinearLayout>

top_layout

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

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tv"
    android:text="这是头条页面"
    android:textColor="#f00"
    />

</LinearLayout>


video_layout

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

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tv"
    android:text="这是视频页面"
    android:textColor="#f00"
    />

</LinearLayout>

item

xlistview_footer

xlistview_header


bean类

public class TabModel {
    private String title;
    private String type;

}


public class Result {

   private List<DataEntity> data;
    private HeaderEntity header;

}

adapter

package animtest.com.example.e531.yuekao_test_demo.adapter;

        import android.content.Context;
        import android.graphics.Bitmap;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

        import com.nostra13.universalimageloader.core.DisplayImageOptions;
        import com.nostra13.universalimageloader.core.ImageLoader;

        import java.util.List;

        import animtest.com.example.e531.yuekao_test_demo.Bean.Result;
        import animtest.com.example.e531.yuekao_test_demo.R;

/**
 * Created by e531 on 2017/10/14.
 */
public class MyAdapter extends BaseAdapter {

    private List<Result.DataEntity>  datas;
    private Context context;
    private DisplayImageOptions options;


    public MyAdapter(List<Result.DataEntity> datas, Context context) {
        this.datas = datas;
        this.context = context;
        options=new DisplayImageOptions.Builder()
                .cacheInMemory(true)//使用内存缓存
                .cacheOnDisk(true)//使用磁盘缓存
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片格式
                .build();
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView==null){
            convertView=View.inflate(context, R.layout.item,null);
            holder=new ViewHolder();
            holder.tvTitle= (TextView) convertView.findViewById(R.id.tv_title);
            holder.img= (ImageView) convertView.findViewById(R.id.img);

            convertView.setTag(holder);
        }else{
            holder=(ViewHolder) convertView.getTag();
        }
        holder.tvTitle.setText(datas.get(position).getTitle());
        if(datas.get(position).getImg()==null || datas.get(position).getImg().equals("")){
            holder.img.setImageResource(R.mipmap.ic_launcher);
        }else{
            //imageLoader加载图片
            ImageLoader.getInstance().displayImage(datas.get(position).getImg(),holder.img,options);
        }
        return convertView;
    }

    class ViewHolder{
        TextView tvTitle;
        ImageView img;
    }
}

MyTask

package animtest.com.example.e531.yuekao_test_demo.Utils;

        import android.os.AsyncTask;

        import java.io.IOException;
        import java.io.InputStream;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.URL;

/**
 * 使用AsyncTask+HttpURLConnection请求数据
 * Created by e531 on 2017/10/12.
 */
public class MyTask extends AsyncTask<String,Void,String> {

    //申请一个接口类对象
    private  Icallbacks icallbacks;

    //将无参构造设置成私有的,使之在外部不能够调用
    private MyTask(){}

    //定义有参构造方法
    public MyTask(Icallbacks icallbacks) {
        this.icallbacks = icallbacks;
    }

    @Override
    protected String doInBackground(String... params) {
        String str="";

        try {
            //使用HttpUrlConnection
            URL url=new URL(params[0]);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            if(connection.getResponseCode()==200){
                InputStream inputStream=connection.getInputStream();
                //调用工具类中的静态方法
                str=StreamToString.streamToStr(inputStream,"utf-8");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //解析,封装到bean,更新ui组件
        icallbacks.updateUiByjson(s);
    }
    //定义一个接口
    public interface Icallbacks{
        /**
         * 根据回传的json字符串,解析并更新页面组件
         * @param jsonstr
         */
        void updateUiByjson(String jsonstr);
    }
}


StreamToString

package animtest.com.example.e531.yuekao_test_demo.Utils;

        import java.io.BufferedReader;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.UnsupportedEncodingException;

/**
 * Created by e531 on 2017/10/12.
 */
public class StreamToString {

    public static String streamToStr(InputStream inputStream,String chartSet){

        StringBuilder builder=new StringBuilder();
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
            String con;
            while ((con=br.readLine())!=null){
                builder.append(con);
            }
            br.close();
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}

MyApplication

package animtest.com.example.e531.yuekao_test_demo;

        import android.app.Application;

        import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
        import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
        import com.nostra13.universalimageloader.core.ImageLoader;
        import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

        import java.io.File;

/**
 * Created by e531 on 2017/10/14.
 */
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        File cacheFile=getExternalCacheDir();
        ImageLoaderConfiguration config=new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
                .threadPoolSize(2)//线程池的数量
                .threadPriority(4)
                .memoryCacheSize(2*1024*1024)//设置内存缓存区大小
                .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
                .diskCache(new UnlimitedDiscCache(cacheFile))//自定义缓存目录
                .writeDebugLogs()//打印日志内容
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
                .build();

        ImageLoader.getInstance().init(config);
    }
}

MyActivity

package animtest.com.example.e531.yuekao_test_demo;

        import android.support.v4.app.Fragment;
        import android.support.v4.widget.DrawerLayout;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.ImageView;
        import android.widget.RadioGroup;
        import android.widget.RelativeLayout;

        import animtest.com.example.e531.yuekao_test_demo.fragments.IndexFragment;
        import animtest.com.example.e531.yuekao_test_demo.fragments.MeFragment;
        import animtest.com.example.e531.yuekao_test_demo.fragments.TopFragment;
        import animtest.com.example.e531.yuekao_test_demo.fragments.VideoFragment;

public class MainActivity extends AppCompatActivity {

    private ImageView imgTitle;
    private RelativeLayout relMenu;
    private DrawerLayout drawerLayout;
    private RadioGroup radioGroup;

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

        drawerLayout = (DrawerLayout) findViewById(R.id.mydrawer);
        imgTitle = (ImageView) findViewById(R.id.img_title);
        radioGroup = (RadioGroup) findViewById(R.id.rel_navigate);

        //侧滑菜单的视图
        relMenu = (RelativeLayout) findViewById(R.id.rel_menu);

        imgTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭,侧滑菜单
                drawerLayout.closeDrawer(relMenu);
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.rb_index){
                    Log.d("zzz","add index fragment ***********");
                    addFragment(new IndexFragment());
                }else if(checkedId==R.id.rb_top){
                    addFragment(new TopFragment());

                }else if(checkedId==R.id.rb_me){
                    addFragment(new MeFragment());

                }else if(checkedId==R.id.rb_video){
                    addFragment(new VideoFragment());
                }
            }
        });
        //默认添加"首页"
        addFragment(new IndexFragment());
    }

    /**
     * 添加fragment到主页面中
     * @param fragment
     */
    public  void addFragment(Fragment fragment){
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content,fragment).commit();

    }
}
 
View

Fragment

ContentFragment

package animtest.com.example.e531.yuekao_test_demo.fragments;

        import android.os.Bundle;
        import android.os.Handler;
        import android.os.Message;
        import android.support.annotation.Nullable;
        import android.support.v4.app.Fragment;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;

        import com.google.gson.Gson;
        import com.google.gson.reflect.TypeToken;

        import java.lang.reflect.Type;
        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.Date;
        import java.util.List;

        import animtest.com.example.e531.yuekao_test_demo.Bean.Result;
        import animtest.com.example.e531.yuekao_test_demo.R;
        import animtest.com.example.e531.yuekao_test_demo.Utils.MyTask;
        import animtest.com.example.e531.yuekao_test_demo.adapter.MyAdapter;
        import animtest.com.example.e531.yuekao_test_demo.view.XListView;

/**
 * Created by e531 on 2017/10/14.
 */
public class ContentFragment  extends Fragment implements XListView.IXListViewListener{

    //扩展的listivew
    private XListView xListView;
    //分类标识
    private String dataType;
    //第几页
    private int pageIndex;
    //请求的数据url
    private String requestUrl="";

    private MyAdapter adapter;
    private List<Result.DataEntity>  datas=new ArrayList<>();
    private int refeshType=1;

    private Handler myHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                xListView.stopRefresh();//关闭
                //设置时间
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:ss");
                String time=simpleDateFormat.format(new Date(System.currentTimeMillis()));
                xListView.setRefreshTime(time);
            }else{
                xListView.stopLoadMore();
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=View.inflate(getActivity(), R.layout.content_layout,null);
        xListView = (XListView) view.findViewById(R.id.xlv);

        //设置支持下拉刷新上拉加载
        xListView.setPullLoadEnable(true);
        xListView.setPullLoadEnable(true);
        //设置接口
        xListView.setXListViewListener(this);

        //得到传过来的参数
        Bundle bundle=getArguments();
        if(bundle!=null){
            dataType=bundle.getString("dataType");
            pageIndex=Integer.parseInt(bundle.getString("pageIndex"));
            //拼接请求的地址
            requestUrl="http://mnews.gw.com.cn/wap/data/news/"+dataType+"/page_"+pageIndex+".json";
            Log.d("zzz","&&&&"+requestUrl);
        }
        requestNetData();
        return view;
    }

    /**
     * 进行网络数据的请求
     */
    private void requestNetData(){

        if(!requestUrl.equals("")){
            MyTask myTask=new MyTask(new MyTask.Icallbacks() {
                @Override
                public void updateUiByjson(String jsonstr) {
                    Log.d("zzz","&&&&"+jsonstr);
                    //进行解析
                    List<Result> results=new ArrayList<>();
                    Type type=new TypeToken<List<Result>>(){}.getType();
                    Gson gson=new Gson();
                    results=gson.fromJson(jsonstr,type);
                    //得到要显示的数据
                    if(refeshType==1){
                        datas.addAll(results.get(0).getData());
                    }else if(refeshType==2){
                        datas.addAll(0,results.get(0).getData());
                    }
                    //设置适配器
                    setAdapter();
                }
            });
            myTask.execute(requestUrl);
        }
    }

    /**
     * 设置适配器
     */
    public void setAdapter(){
        if(adapter==null){
            adapter=new MyAdapter(datas,getActivity());
            xListView.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
    }

    //刷新
    @Override
    public void onRefresh() {
        refeshType=2;
        pageIndex++;
        requestUrl="http://mnews.gw.com.cn/wap/data/news/"+dataType+"/page_"+pageIndex+".json";
        requestNetData();
        myHandler.sendEmptyMessageDelayed(1,1000);
    }

    //加载更多
    @Override
    public void onLoadMore() {
        refeshType=1;
        pageIndex++;
        requestUrl="http://mnews.gw.com.cn/wap/data/news/"+dataType+"/page_"+pageIndex+".json";
        requestNetData();
        myHandler.sendEmptyMessageDelayed(2,1000);
    }
}

IndexFragment

package animtest.com.example.e531.yuekao_test_demo.fragments;

        import android.os.Bundle;
        import android.support.annotation.Nullable;
        import android.support.design.widget.TabLayout;
        import android.support.v4.app.Fragment;
        import android.support.v4.app.FragmentManager;
        import android.support.v4.app.FragmentPagerAdapter;
        import android.support.v4.view.ViewPager;
        import android.util.Log;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;

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

        import animtest.com.example.e531.yuekao_test_demo.Bean.TabModel;
        import animtest.com.example.e531.yuekao_test_demo.R;

/**
 * Created by e531 on 2017/10/14
 *
 */
public class IndexFragment extends Fragment {

    private ViewPager viewPager;
    private TabLayout tabLayout;
    private List<TabModel> lists=new ArrayList<TabModel>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.index_layout,null);

        viewPager = (ViewPager) v.findViewById(R.id.vp);
        tabLayout = (TabLayout) v.findViewById(R.id.mytab);

        //tab标题信息
        intTabData();
        //设置适配器 ,,得到子fragment的管理者,使用getChildFragmentManager
        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
        //建立关联
        tabLayout.setupWithViewPager(viewPager);
        //指定加载的页数 http://blog.csdn.net/qq_29134495/article/details/51548002
        viewPager.setOffscreenPageLimit(lists.size());

        return v;
    }

    /**
     * 初使化tab导航
     */
    private void intTabData() {
        lists.add(new TabModel("数据新闻","xbsjxw"));
        lists.add(new TabModel("快讯","txs"));
        lists.add(new TabModel("头条","toutiao"));
        lists.add(new TabModel("精编公告","news/mobile/jbgg"));
        lists.add(new TabModel("美股","news/mobile/mgxw"));
        lists.add(new TabModel("港股","news/mobile/ggxw"));
        lists.add(new TabModel("基金","news/mobile/jjxw"));
        lists.add(new TabModel("理财","news/mobile/lcxw"));

    }

    class  MyAdapter extends FragmentPagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        //获取tab导航文本
        @Override
        public CharSequence getPageTitle(int position) {
            return lists.get(position).getTitle();
        }

        @Override
        public Fragment getItem(int position) {

            Log.d("zzz","pager adapter ***********"+position);
            Bundle bundle=new Bundle();
            bundle.putString("dataType",lists.get(position).getType());
            bundle.putString("pageIndex","1");

            ContentFragment contentFragment=new ContentFragment();
            contentFragment.setArguments(bundle);

            return contentFragment;
        }

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

MeFragment
TopFragment
VideoFragment

<--添加权限-->


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值