欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

androidx+viewpage+tablayout+json开发(加载图片和视频)

程序员文章站 2022-04-01 10:54:25
本文针对androidx完成任务 之前文的sdk版本陈旧 首先列举本文的代码结构图将json数据放进本地assent路径下用于读取首先创建实体类用于解析json 这段可以去在线解析网站生成实体类需要注意的一点就是实体类需要实现可序列化接口 由于实体类中成员变量过多这里暂时不粘贴代码public class Godv implements Serializable接下来写整个应用的布局main-xml

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

androidx+viewpage+tablayout+json开发(加载图片和视频)

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

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

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

public class Godv implements Serializable

接下来写整个应用的布局

main-xml

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

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/transparent"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/colorAccent"
        app:tabIndicatorFullWidth="false"
        app:tabMaxWidth="@dimen/de_0"
        app:tabRippleColor="@color/transparent"
        app:tabSelectedTextColor="@color/colorPrimary"
        app:tabTextColor="@color/f2_bc">

    </com.google.android.material.tabs.TabLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#E4E4E4">

    </View>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </androidx.viewpager.widget.ViewPager>

</LinearLayout>

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<Godv> mList = null;
    private List<Fragment> 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布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/tv_fragment_text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/de_0"
        android:layout_weight="1"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:textColor="@color/f1_bc" />

    <ImageView
        android:id="@+id/iv_fragment_img"
        android:layout_width="match_parent"
        android:layout_height="@dimen/de_0"
        android:layout_weight="5"
        android:background="@color/wv_bc" />

    <WebView
        android:id="@+id/wv_fragment_video"
        android:layout_width="match_parent"
        android:layout_height="@dimen/de_0"
        android:layout_weight="5" />

</LinearLayout>

工具默认建立的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添加权限 允许设备联网

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

<application 下添加

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开发(加载图片和视频)

最终的成品 请忽略配色

androidx+viewpage+tablayout+json开发(加载图片和视频)

本文地址:https://blog.csdn.net/we1less/article/details/107784615