模拟今日头条

记得添加依赖:
compile 'com.android.support:design:25.3.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.github.bumptech.glide:glide:3.8.0'
compile 'org.webjars.npm:react-imageloader:2.1.0'
compile 'org.xutils:xutils:3.5.0'
还要导入xlistview的model:

见一个继承Application类   记得在AndroidManifest.xml中注册name

-------------------------------------------------------------------------------------------------------------------

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

        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);
    }

}

-------------------------------------------------------------------------------------------------------------------

1.MainActivity
public class MainActivity extends AppCompatActivity {
    private TabLayout tab;
    private ViewPager vp;
    private List listTitle;
    private List fragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }
    private void initView() {
        tab = (TabLayout) findViewById(R.id.tab);
        vp = (ViewPager) findViewById(R.id.vp);
    }

    private void initData() {
        listTitle = TitleBean.getAllTitle();

        for (int i = 0; i < listTitle.size(); i++) {

          MyFragment myFragment = new MyFragment();
            fragmentList.add(myFragment);
        }
        MyViewPagerAdapter adapter = new MyViewPagerAdapter(getSupportFragmentManager(), fragmentList, listTitle);
        vp.setAdapter(adapter);
        tab.setupWithViewPager(vp);
    }

}

-------------------------------------------------------------------------------------------------------------------

1.MainActivity 布局

    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
            android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#EA2000">

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="8dp"
            android:text="今日头条"
            android:textColor="#ffffff"
            android:textSize="30sp" />
   

            android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable"
        app:tabIndicatorColor="#EA2000"
        app:tabSelectedTextColor="#EA2000"
        >

            android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/vp"
        >

-------------------------------------------------------------------------------------------------------------------

//判断网络的工具类
public class ConnectionUtil {
 
    /*  
    * 判断网络连接是否已开  
    *true 已打开  false 未打开  
    * */  
    public static boolean isConn(Context context){
        boolean bisConnFlag=false;  
        ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if(network!=null){  
            bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();  
        }  
        return bisConnFlag;  
    }  
 
 
    /*  
    * 打开设置网络界面  
    * */  
    public static void setNetworkMethod(final Context context){  
        //提示对话框  
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {  
 
            @Override  
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub  
                Intent intent=null;  
                //判断手机系统的版本  即API大于10 就是3.0或以上版本  
                if(android.os.Build.VERSION.SDK_INT>10){  
                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                }else{  
                    intent = new Intent();  
                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
                    intent.setComponent(component);  
                    intent.setAction("android.intent.action.VIEW");  
                }  
                context.startActivity(intent);  
            }  
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {  
 
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                // TODO Auto-generated method stub  
                dialog.dismiss();  
            }  
        }).show();  
    }  

}

-------------------------------------------------------------------------------------------------------------------

//fragment的类  
public class MyFragment extends Fragment {


    private SQLiteDatabase db;
    private String json;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.item_layout, container, false);
    }

    private XListView xLv;

    //private List list=new ArrayList<>();
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        xLv = (XListView) getView().findViewById(R.id.xLv);

        if (!ConnectionUtil.isConn(getContext())) {

          //没网就进行网络设置
            ConnectionUtil.setNetworkMethod(getContext());
            //从缓存读取
           // queryData();

        } else {
          //请求数据的方法
            getDataFromServer();
        }
    }
    //查询数据库里面的数据

    private void queryData() {
        Cursor cursor =  db.query("news", null, null, null, null, null, null,null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                json = cursor.getString(cursor.getColumnIndex("content"));
            }
            Gson gson = new Gson();
            Bean bean = gson.fromJson(json, Bean.class);
            List data = bean.getData();

            MyListViewAdapter  adapter=new MyListViewAdapter(getContext(),data);
            xLv.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }
    //插入数据到数据库

    private void insertData(String str){
        MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
        db = mySQLiteOpenHelper.getWritableDatabase();
        ContentValues values=new ContentValues();
        values.put("content",str);
        db.insert("news",null,values);
    }

    private void getDataFromServer() {
        String url = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
        RequestParams params = new RequestParams();
        params.setUri(url);
        x.http().get(params, new Callback.CommonCallback() {

            @Override
            public void onSuccess(String result) {

                if (result != null) {
                    //插入数据
                    insertData(result);
                    Gson gson = new Gson();
                    Bean bean = gson.fromJson(result, Bean.class);
                    List data = bean.getData();

                   MyListViewAdapter adapter = new MyListViewAdapter(getContext(), data);
                    xLv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}

-------------------------------------------------------------------------------------------------------------------

//fragment的布局

    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    android:id="@+id/xLv"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

-------------------------------------------------------------------------------------------------------------------

//FragmentPagerAdapter 适配器
public class MyViewPagerAdapter extends FragmentPagerAdapter {

    private List fragmentList;
    private List titleList;

    public MyViewPagerAdapter(FragmentManager fm, List fragmentList, List titleList) {
        super(fm);
        this.fragmentList = fragmentList;
        this.titleList = titleList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

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

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

}

-------------------------------------------------------------------------------------------------------------------

//BaseAdapter 的适配器
public class MyListViewAdapter extends BaseAdapter {
    private Context context;
    private List list;

    public MyListViewAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int position) {
        return list.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 = LayoutInflater.from(context).inflate(R.layout.list_layout, null);
            holder = new ViewHolder();
            holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
            holder.tvContent = (TextView) convertView.findViewById(R.id.tvContent);
            holder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);

            convertView.setTag(holder);
        } else {
            holder= (ViewHolder) convertView.getTag();
        }

        holder.tvTitle.setText(list.get(position).getNews_title());
        holder.tvContent.setText(list.get(position).getNews_summary());
        x.image().bind(holder.ivIcon,list.get(position).getPic_url());
        return convertView;
    }

    static class ViewHolder {
        private TextView tvTitle, tvContent;
        private ImageView ivIcon;
    }

}

-------------------------------------------------------------------------------------------------------------------

//BaseAdapter的布局

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

            android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />

            android:id="@+id/tvContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

            android:id="@+id/ivIcon"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

-------------------------------------------------------------------------------------------------------------------

//SQLite的工具类
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    public MySQLiteOpenHelper(Context context) {
        super(context, "news.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table news(id Integer primary key autoincrement,content text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

-------------------------------------------------------------------------------------------------------------------

//Tablayout的标题工具类
public class TitleBean {

    private int id;
    private String name;


    public static  List getAllTitle(){

        List listTitle=new ArrayList<>();
        listTitle.add("推荐");
        listTitle.add("科技");
        listTitle.add("电影");
        listTitle.add("娱乐");
        listTitle.add("头条");
        listTitle.add("游戏");
        listTitle.add("逃狱");
        listTitle.add("历史");
        listTitle.add("民俗");
        return listTitle;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "TitleBean{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
//网络请求数据的实体类
自己创建

你可能感兴趣的:(模拟今日头条)