ViewPager引导页,Xlv网络获取,频道管理

MainActivity.java

public class MainActivity extends AppCompatActivity {  //图片引导页

    private ViewPager pager;
    private Button button;
    ArrayList<Integer> list;
    private SharedPreferences sharedPreferences;

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

         pager = findViewById(R.id.pager);
         button = findViewById(R.id.btn);

        list = new ArrayList<>();
        list.add(R.drawable.e);
        list.add(R.drawable.r);
        list.add(R.drawable.t);
        list.add(R.drawable.y);

        sharedPreferences = getSharedPreferences("ss", MODE_PRIVATE);

        Boolean aa=sharedPreferences.getBoolean("a",false);
        if (aa){
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }

        pager.setAdapter(new Madapter());
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:

                        button.setVisibility(View.GONE);
                        break;

                    case 1:
                        button.setVisibility(View.GONE);
                        break;
                    case 2:
                        button.setVisibility(View.GONE);
                        break;
                    case 3:
                        button.setVisibility(View.VISIBLE);
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putBoolean("a",true);
                edit.commit();

                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });


    }

    class Madapter extends PagerAdapter{

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

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

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView imageView = new ImageView(MainActivity.this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setImageResource(list.get(position));
            container.addView(imageView);

            return imageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }
}

activity_main.xml

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

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


        </android.support.v4.view.ViewPager>
        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="跳过"
            android:layout_marginTop="-200dp"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            />
    </LinearLayout>

SecondActivity.java

public class SecondActivity extends BaseActivity{   //主页面
    private ViewPager pager;
    private TabLayout tabLayout;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle toggle;


    @Override
    protected int getContentView() {
        return R.layout.second;
    }

    @Override
    protected void findView() {
        pager = findViewById(R.id.pager);
        tabLayout = findViewById(R.id.tab);
        drawerLayout = findViewById(R.id.draw);

    }

    @Override
    protected void initData() {
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                Fragment fragment=new Fragment();
                switch (position){
                    case 0:
                        fragment=new Afragment();
                        break;
                    case 1:
                        fragment=new Bfragment();
                        break;
                    case 2:
                        fragment=new Cfragment();
                        break;
                    case 3:
                        fragment=new Dfragment();
                        break;
                }
                return fragment;
            }

            @Override
            public int getCount() {
                return 4;
            }
        });
        loadTabLayout();

        setDrawerLayout();
    }

    private void setDrawerLayout() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        toggle =new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
        toggle.syncState();
        drawerLayout.addDrawerListener(toggle);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (toggle.onOptionsItemSelected(item)){
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadTabLayout() {
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());

        tabLayout.setupWithViewPager(pager);
        tabLayout.getTabAt(0).setText("蒸");
        tabLayout.getTabAt(1).setText("蒸");
        tabLayout.getTabAt(2).setText("日");
        tabLayout.getTabAt(3).setText("上");
    }
}

second.xml



 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/draw"
            android:orientation="vertical">
        
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <android.support.v4.view.ViewPager
                    android:id="@+id/pager"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="9"/>
        
                <android.support.design.widget.TabLayout
                    android:id="@+id/tab"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"/>
            </LinearLayout>
            <fragment
                class="fanruiqi.bwie.com.yuekaolx.fragment.Efragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="start"/>
        
        </android.support.v4.widget.DrawerLayout>

Afragment.java

public class Afragment extends Fragment{   //xlv显示
    Dao dao;
    private XListView xListView;
    public int page=1;
    public String urlString="http://www.xieast.com/api/news/news.php?type=top&page="+page+"";
    private MyBaseAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.afrag, null);

        dao = new Dao(getActivity());
        //dao.query();
        //dao.insert("aa","aaa");
        xListView = view.findViewById(R.id.xlv);

        adapter = new MyBaseAdapter(getLayoutInflater());
        xListView.setAdapter(adapter);

        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                page=1;
                initData(urlString);
            }

            @Override
            public void onLoadMore() {

                initData(urlString);
            }
        });

        initData(urlString);
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String title=adapter.getList().get(i-1).getTitle();
                String img = adapter.getList().get(i - 1).getThumbnail_pic_s();

                Intent intent = new Intent(getActivity(), ThredActivity.class);
                intent.putExtra("title",title);
                intent.putExtra("img",img);
                startActivity(intent);
            }
        });
        return view;
    }

    private void initData(String urlString) {
        new AsyncTask<String, Void, List<ResponseBean.DataBean>>() {
            @Override
            protected List<ResponseBean.DataBean> doInBackground(String... strings) {

                String datas = Http.requestData(strings[0]);
                ResponseBean responseBean = new Gson().fromJson(datas, ResponseBean.class);
                if (responseBean!=null){
                    return responseBean.getData();
                }
                return null;
            }

            @Override
            protected void onPostExecute(List<ResponseBean.DataBean> responseBeans) {
                super.onPostExecute(responseBeans);

                caseR((ArrayList<ResponseBean.DataBean>) responseBeans);
                closeXlv();
            }
        }.execute(urlString);
    }

    private void caseR(ArrayList<ResponseBean.DataBean> bs){
        if (page==1){
            adapter.setDatas(bs);
        }else {
            adapter.addDatas(bs);

        }
    }

    private void closeXlv(){
        page++;
        xListView.stopRefresh();
        xListView.stopLoadMore();
    }
}

Bfragment.java

public class Bfragment extends Fragment{   //频道管理

    private String jsonStr;
    ArrayList<ChannelBean> list;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.bfrag, null);

        Button button = view.findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (list==null){
                    list = new ArrayList<>();
                    list.add(new ChannelBean("热点",true));
                    list.add(new ChannelBean("军事",true));
                    list.add(new ChannelBean("八卦",true));
                    list.add(new ChannelBean("游戏",true));
                    list.add(new ChannelBean("宠物",true));
                    list.add(new ChannelBean("汽车",false));
                    list.add(new ChannelBean("热卖",false));
                    list.add(new ChannelBean("外卖",false));
                    list.add(new ChannelBean("太阳花",false));
                    list.add(new ChannelBean("九三",false));
                    list.add(new ChannelBean("八嘎",false));
                    list.add(new ChannelBean("色昂",false));
                    ChannelActivity.startChannelActivity((AppCompatActivity) getActivity(),list);

                    Gson gson = new Gson();
                    String jsonArray = gson.toJson(list);
                    Intent intent = new Intent(getActivity(), ChannelActivity.class);
                    intent.putExtra(RESULT_JSON_KEY, jsonArray);
                    startActivityForResult(intent, REQUEST_CODE);

                }else if(jsonStr!=null){

                    ChannelActivity.startChannelActivity((AppCompatActivity) getActivity(),jsonStr);
                }
            }
        });


        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== REQUEST_CODE&&resultCode==ChannelActivity.RESULT_CODE) {
            jsonStr = data.getStringExtra(RESULT_JSON_KEY);
        }
    }
}

ThredAcrtivity.java

public class ThredActivity extends AppCompatActivity{
    private ViewPager pager;
    public String urlString="http://www.xieast.com/api/banner.php";
    private BannerAdapter adapter;

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

        pager = findViewById(R.id.pager);
        ImageView imageView = findViewById(R.id.image);
        TextView textView = findViewById(R.id.textview);

        Intent intent = getIntent();
        String img = intent.getStringExtra("img");
        String title = intent.getStringExtra("title");

        textView.setText(title);
        ImageLoader.getInstance().displayImage(img,imageView);

        adapter = new BannerAdapter(getLayoutInflater());
        pager.setAdapter(adapter);
        initData(urlString);
    }

    private void initData(String urlString) {

        new AsyncTask<String, Void, ArrayList<BannerBean.DataBean>>() {
            @Override
            protected ArrayList<BannerBean.DataBean> doInBackground(String... strings) {
                String datas = Http.requestData(strings[0]);
                BannerBean bannerBean = new Gson().fromJson(datas, BannerBean.class);

                if (bannerBean!=null){
                    return (ArrayList<BannerBean.DataBean>) bannerBean.getData();
                }
                return null;
            }

            @Override
            protected void onPostExecute(ArrayList<BannerBean.DataBean> dataBeans) {
                super.onPostExecute(dataBeans);
                adapter.setDatas(dataBeans);
            }
        }.execute(urlString);
    }
}

BaseActivity

public abstract class BaseActivity extends AppCompatActivity{  //基类

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        findView();
        initData();
    }

    protected abstract int getContentView();
    protected abstract void findView();
    protected abstract void initData();
}

App.java

public class App extends Application{  //网络加载图片
    @Override
    public void onCreate() {
        super.onCreate();
        //BitmapDisplayer bitmapDisplayer = new CircleBitmapDisplayer();
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                //.displayer(bitmapDisplayer)
                .showImageOnLoading(R.drawable.ic_launcher)
                .showImageForEmptyUri(R.drawable.ic_launcher)
                .cacheInMemory(true)
                .build();


        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration
                .Builder(this)
                .defaultDisplayImageOptions(options)
                .build();

        ImageLoader.getInstance().init(configuration);

    }
}

Http.java

public class Http {       //网络请求字符串数据,外部类,被内部调用
    public static String requestData(String string){
        String getgson=null;
        try {
            URL url = new URL(string);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(50*1000);
            urlConnection.setReadTimeout(50*1000);
            int responseCode = urlConnection.getResponseCode();
            if(responseCode==200){
                String gsonString = stream2String(urlConnection.getInputStream());
                getgson=gsonString;

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

    private static String stream2String(InputStream inputStream) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            for (String tmp = bufferedReader.readLine(); tmp!=null; tmp=bufferedReader.readLine()) {
                stringBuilder.append(tmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }
}

SqliteHelper.java

public class SqliteHelper extends SQLiteOpenHelper{    //数据库建表
    public SqliteHelper(Context context) {
        super(context,"user.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table users(id integer primary key autoincrement,name text,age text)");
        db.execSQL("insert into users (name,age) values(?,?)",new String[]{"frq","frq"});
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

Dao.java

public class Dao {   //操作数据库

        private final SqliteHelper sqliteHelper;
        SQLiteDatabase database;
    
    
        public Dao(Context context) {
            sqliteHelper = new SqliteHelper(context);
            database = sqliteHelper.getReadableDatabase();
    
        }
    
    
        public ArrayList<Sqlite> query() {
            Cursor cursor = database.rawQuery("select * from users", null);
            ArrayList<Sqlite> list = new ArrayList<>();
    
            while (cursor.moveToNext()){
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String age = cursor.getString(cursor.getColumnIndex("age"));
    
                Sqlite sqlite = new Sqlite(name, age);
                list.add(sqlite);
            }
            return list;
        }
    
        public void insert(String aa, String aaa) {
    
            database.execSQL("insert into users(name,age) values(?,?)",new Object[]{aa,aaa});
        }
    }

BannerAdapter

public class BannerAdapter extends PagerAdapter{   //加载viewpager图片
    private LayoutInflater layoutInflater;
    ArrayList<BannerBean.DataBean> list;

    public BannerAdapter(LayoutInflater layoutInflater) {
        this.layoutInflater = layoutInflater;
        list = new ArrayList<>();
    }

    public void setDatas(ArrayList<BannerBean.DataBean> datas) {
        list.addAll(datas);
        notifyDataSetChanged();
    }

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

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

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(layoutInflater.getContext());
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageLoader.getInstance().displayImage(list.get(position).getImg(),imageView);
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}

MyBaseAdapter.java

public class MyBaseAdapter extends BaseAdapter{  //加载xlv的adapter
    private LayoutInflater layoutInflater;
    private final ArrayList<ResponseBean.DataBean> list;

    public MyBaseAdapter(LayoutInflater layoutInflater) {
        this.layoutInflater = layoutInflater;
        list = new ArrayList<>();
    }

    public ArrayList<ResponseBean.DataBean> getList() {
        return list;
    }

    public void setDatas(ArrayList<ResponseBean.DataBean> datas) {
        list.clear();
        list.addAll(datas);
        notifyDataSetChanged();
    }
    public void addDatas(ArrayList<ResponseBean.DataBean> bs) {
        list.addAll(bs);
        notifyDataSetChanged();
    }

    /*public static final int ONE=0;
    public static final int TWO=1;
    public static final int THREE=2;

    @Override
    public int getItemViewType(int position) {
        ResponseBean.DataBean dataBean = list.get(position);
        if (!TextUtils.isEmpty(dataBean.getThumbnail_pic_s03())){
            return THREE;
        }else if (!TextUtils.isEmpty(dataBean.getThumbnail_pic_s02())){
            return TWO;
        }else {
            return ONE;
        }

    }

    @Override
    public int getViewTypeCount() {
        return 3;
    }*/

    @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 View getView(int i, View view, ViewGroup viewGroup) {


        if (getItemViewType(i)==ONE){
            ViewHolder viewHolder=null;
            if (view==null){
                viewHolder = new ViewHolder();
                view = layoutInflater.inflate(R.layout.item, viewGroup, false);

                viewHolder.textView = view.findViewById(R.id.text);
                viewHolder.imageView = view.findViewById(R.id.img);
                view.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder) view.getTag();

            }
            viewHolder.textView.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s(),viewHolder.imageView);
        }else if (getItemViewType(i)==TWO){

            ViewHolder2 viewHolder2=null;
            if (view==null){
                viewHolder2 = new ViewHolder2();
                view = layoutInflater.inflate(R.layout.item2, viewGroup, false);

                viewHolder2.textView = view.findViewById(R.id.text);
                viewHolder2.imageView = view.findViewById(R.id.img);
                viewHolder2.imageView2 = view.findViewById(R.id.img2);
                view.setTag(viewHolder2);
            }else {
                viewHolder2 = (ViewHolder2) view.getTag();

            }
            viewHolder2.textView.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s(),viewHolder2.imageView);
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s02(),viewHolder2.imageView2);
        }else {

            ViewHolder3 viewHolder3=null;
            if (view==null){
                viewHolder3 = new ViewHolder3();
                view = layoutInflater.inflate(R.layout.item3, viewGroup, false);

                viewHolder3.textView = view.findViewById(R.id.text);
                viewHolder3.imageView = view.findViewById(R.id.img);
                viewHolder3.imageView2 = view.findViewById(R.id.img2);
                viewHolder3.imageView3 = view.findViewById(R.id.img3);
                view.setTag(viewHolder3);
            }else {
                viewHolder3 = (ViewHolder3) view.getTag();

            }
            viewHolder3.textView.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s(),viewHolder3.imageView);
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s02(),viewHolder3.imageView2);
            ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s03(),viewHolder3.imageView3);

        }
        return view;
    }

    class ViewHolder{

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

        private TextView textView;
        private ImageView imageView;
        private ImageView imageView2;
    }
    class ViewHolder3{

        private TextView textView;
        private ImageView imageView;
        private ImageView imageView2;
        private ImageView imageView3;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值