androidx+viewpage+tablayout+json+加载图片+加载视频

本文针对androidx完成任务 之前文的sdk版本陈旧 首先列举本文的代码结构图

androidx+viewpage+tablayout+json+加载图片+加载视频_第1张图片

将json数据放进本地assent路径下用于读取

首先创建实体类用于解析json 这段可以去在线解析网站生成实体类

需要注意的一点就是实体类需要实现可序列化接口 由于实体类中成员变量过多这里暂时不粘贴代码

public class Godv implements Serializable

接下来写整个应用的布局

main-xml




    

    

    

    

    

    

main-activity 包含加载本地文件内容的方法

import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List mList = null;
    private List mFragmentList = new ArrayList();
    private String[] mTitles = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //读取数据
        String json = getFromAssets("details.txt");
        Godv[] array = new Gson().fromJson(json, Godv[].class);
        mList = Arrays.asList(array);
        mTitles = new String[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            mTitles[i] = mList.get(i).getName().substring(0, 1);
            Bundle bundle = new Bundle();
            bundle.putSerializable("godv", mList.get(i));
            mFragmentList.add(BlankFragment.newInstance("godv", bundle));
        }
        initView();
    }

    private void initView() {
        TabLayout tab_layout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.viewPager);
        MyAdapter fragmentAdater = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(fragmentAdater);
        tab_layout.setupWithViewPager(viewPager);
    }

    public class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

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

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

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }
    }
//用于加载json的方法
    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            return "没找到";
        }
    }

}

利用as新建fragment(bank)

写item-xml布局




    
    

    

    

工具默认建立的fragment是一个实现类 里面具有返回一个fragment对象的方法 加载布局的方法

BankFragment

import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, Bundle args) {
        BlankFragment fragment = new BlankFragment();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_blank, container, false);
        Bundle arguments = getArguments();
        Godv godv = (Godv) arguments.get("godv");
        TextView tv = v.findViewById(R.id.tv_fragment_text);
        WebView wv_fragment_video = v.findViewById(R.id.wv_fragment_video);
        ImageView iv_fragment_img = v.findViewById(R.id.iv_fragment_img);
        Glide.with(v).load(godv.getThumbnail()).into(iv_fragment_img);
        WebSettings settings = wv_fragment_video.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //支持js
        settings.setJavaScriptEnabled(true);
        // 支持插件
        settings.setPluginState(WebSettings.PluginState.ON);
        //支持自动加载图片
        settings.setLoadsImagesAutomatically(true);
        //将图片调整到适合webview的大小无效
        settings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        settings.setLoadWithOverviewMode(true);
        wv_fragment_video.setWebChromeClient(new WebChromeClient());
        // 加载链接
        wv_fragment_video.loadUrl(godv.getVideo());
        tv.setText(godv.getText());
        return v;
    }
}

AndroidManifest.xml添加权限 允许设备联网

 

android:usesCleartextTraffic="true"

build.gradle下 dependencies { 添加依赖  Gson(处理json)和glide(加载图片) 

    implementation 'com.github.bumptech.glide:glide:4.7.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
    implementation 'com.google.code.gson:gson:2.6.2'

在项目的build.gradle 搭建梯子阿里云的

将 jcenter() 注释掉换成下面的  这里注意需要修改的有两处

//        jcenter()
        maven{ url'http://maven.aliyun.com/nexus/content/groups/public/' }
        maven{ url'http://maven.aliyun.com/nexus/content/repositories/jcenter'}

androidx+viewpage+tablayout+json+加载图片+加载视频_第2张图片

最终的成品 请忽略配色

androidx+viewpage+tablayout+json+加载图片+加载视频_第3张图片

你可能感兴趣的:(安卓基础学习,android)