使用片段和JSON在TabLayout上遇到问题

时间:2018-02-15 02:36:15

标签: android android-layout

您好我已经尝试了一段时间来解决这个问题并检查了很多帖子。当我切换到新选项卡时,我只有XML布局显示时遇到此问题。虽然当我开始第一个标签和片段时,json内容显示我喜欢的方式。我不知道如何为新标签更改json内容。

片段

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 */
public class TVFragment extends Fragment {


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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.tv_activity, container, false);


        ArrayList<String> media = new ArrayList<String>();
        media.add("movie1");
        media.add("movie2");
        media.add("movie3");


        this.loadMovieInfo(media);
//        loadMoviePoster(media);


        return rootView;
}


    private void loadMovieInfo(ArrayList<String> media) {

        Random random = new Random();


        int x = (int) random.nextInt(media.size()) * 1;

        //Use Ion to get json info for movie from movie/tv api.

        Ion.with(this)
                .load("http://www.omdbapi.com/?t=" + media.get(x)
                        + "&apikey0000")
                .asString()
                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                        try {
                            // create json object
                            JSONObject json = new JSONObject(result);
                            //get json title and poster from the json object.
                            String name = json.getString("Title");
                            String urlString = json.getString("Poster");

                            //get TextView to display title
                            TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
                            mediaName.setText(name);

                            /* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
                                this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
                            */
                            new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);

                        } catch (JSONException jsone) {
                            Log.wtf("Json Import problems", jsone);
                        }
                    }
                });
    }

}

MainActivity

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Samuel on 2/12/2018.
 */

public class TechnologyResultsActivity extends AppCompatActivity {

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

        // Set the content of the activity to use the tv_activitylayout file
        setContentView(R.layout.tab_viewpager_activity);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

        MediaTypeAdapter adapter = new MediaTypeAdapter(getSupportFragmentManager(),getApplicationContext());

        viewPager.setAdapter(adapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(viewPager);

    }

}

适配器

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * Created by Samuel on 2/14/2018.
 */

public class MediaTypeAdapter extends FragmentPagerAdapter {


    public MediaTypeAdapter(FragmentManager fragmentManager, Context applicationContext){
        super(fragmentManager);
    }



    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new TVFragment();
        } else if (position == 1) {
            return new MovieFragment();
        }
        else {
            return new MovieFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        if(position == 0){
            return  "TV";
        } else {
            return "MOVIES";
        }

    }
}

tablayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/colorPrimary"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout

        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed">

    </android.support.design.widget.TabLayout>

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

    </android.support.v4.view.ViewPager>

</LinearLayout>

movie_activity布局

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



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="bottom"
        android:paddingBottom="16dp">


        <ImageView
            android:id="@+id/poster"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:paddingTop="16dp"
            android:paddingBottom="16dp"
            tools:src="@drawable/poster"
            android:layout_weight="1"

            />


        <ScrollView
            android:id="@+id/synopsis_scroll"
            android:layout_width="match_parent"
            android:layout_height="81dp"
            android:padding="8dp">

            <TextView
                android:id="@+id/synopsis_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:text="Academy Award nominee, heart-warming, hit comedy from producer Judd Apatow (Bridesmaids and Trainwreck). The Big Sick is based on the real-life courtship between Pakistan-born comedian Kumail Nanjiani (Nanjiani) and grad student Emily Gordon (Zoe Kazan) who fall in love but struggle while dealing with Emily's mysterious illness and their families culture clash. Also staring Ray Romano and Holly Hunter. Included with Prime."/>

        </ScrollView>

    </LinearLayout>


</LinearLayout>

1 个答案:

答案 0 :(得分:0)

你必须创建一个新的类moviefragment并且必须编写代码来获取电影。

public class MovieFragment extends Fragment{
TechnologyResultsActivity technology;
Context context;
 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
        technology= (TechnologyResultsActivity) context;
    }
    public static Fragment newInstance(Bundle bundle){
        MovieFragment movie=new MovieFragment();
        if(bundle!=null){
            movie.setArguments(bundle);
        }
        return movie;
    }

@Override
    public void onResume() {
        super.onResume();
// this will only called when fragment is visible to user
        if(isVisible()) {
            if (Constant.isInternetConnected(homeActivity)) {
                ArrayList<String> media = new ArrayList<String>();
        media.add("movie1");
        media.add("movie2");
        media.add("movie3");
loadMovieInfo(media)

            } else {
                Toast.makeText(homeActivity, "No Internet Connection", Toast.LENGTH_SHORT).show();
            }
        }


    }

private void loadMovieInfo(ArrayList<String> media) {

        Random random = new Random();


        int x = (int) random.nextInt(media.size()) * 1;

        //Use Ion to get json info for movie from movie/tv api.

        Ion.with(this)
                .load("http://www.omdbapi.com/?t=" + media.get(x)
                        + "&apikey0000")
                .asString()
                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                        try {
                            // create json object
                            JSONObject json = new JSONObject(result);
                            //get json title and poster from the json object.
                            String name = json.getString("Title");
                            String urlString = json.getString("Poster");

                            //get TextView to display title
                            TextView mediaName = (TextView) getActivity().findViewById(R.id.synopsis_text_view);
                            mediaName.setText(name);

                            /* create new DownloadImageTask class for displaying image from url. Picasso API can be used instead if wanted to view picture as well.
                                this needs to be used since the app will crash due to nature of threading, so AsyncTask is implemented.
                            */
                            new DownloadImageTask((ImageView) getActivity().findViewById(R.id.poster)).execute(urlString);

                        } catch (JSONException jsone) {
                            Log.wtf("Json Import problems", jsone);
                        }
                    }
                });

    }

}