viewpager внутри вкладки ничего не показывает

#android #android-viewpager

#Android #android-viewpager

Вопрос:

мне нужна помощь, чтобы попробовать работу моего viewpager, я поместил свой код, чтобы помочь мне найти ошибку. Спасибо

У меня есть этот фрагмент

 import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.JsonReader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.TabHost;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class ClasesFragment extends Fragment {

    private static int NUM_PAGES = 13;
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;
    private ProgressDialog pDialog;
    private JsonReader reader;
    protected TableLayout MainLayoutDatos;
    protected View view;

    private TableRow[] datosTableRows;

    private String razon = "";
    boolean success = false;

    private ArrayList<String> nombresEstaciones = new ArrayList<String>();
    private ArrayList<ArrayList<Number>> aDatosVolList = new ArrayList<ArrayList<Number>>();
    private ArrayList<ArrayList<Number>> aDatosNivelList = new ArrayList<ArrayList<Number>>();
    private ArrayList<ArrayList<Number>> aFechasList = new ArrayList<ArrayList<Number>>();
    public ProgressDialog pdLoading;

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

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\A");
        return s.hasNext() ? s.next() : "";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_clases, container, false);
        TabHost tabhost = (TabHost) view.findViewById(R.id.tabHostClases);
        tabhost.setup();
        TabHost.TabSpec spec1 = tabhost.newTabSpec("DATOS");
        TabHost.TabSpec spec2 = tabhost.newTabSpec("GRÁFICOS");
        spec1.setIndicator("DATOS");
        spec1.setContent(R.id.pestanaDatosEmb);
        spec2.setIndicator("GRÁFICOS");
        spec2.setContent(R.id.pestanaGrafEmb);
        tabhost.addTab(spec1);
        tabhost.addTab(spec2);

        HorizontalScrollView pestanaDatos = (HorizontalScrollView) view.findViewById(R.id.pestanaDatosEmb);
        //Create the layout para pestanaDatosEmb
        MainLayoutDatos = new TableLayout(view.getContext());
        MainLayoutDatos.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
        MainLayoutDatos.setStretchAllColumns(true);
        pestanaDatos.addView(MainLayoutDatos);

        NUM_PAGES = 5;
        mPager = (ViewPager) view.findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getActivity().getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);

        pdLoading = new ProgressDialog(getActivity());

        try {
            ConnectivityManager connMgr = (ConnectivityManager)
                    getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

            if (networkInfo != null amp;amp; networkInfo.isConnected()) {
                new JsonTask().execute(new URL("http://www.myhost.com/android/clases"));
           } else {
                Toast.makeText(getActivity(), "Error de conexión", Toast.LENGTH_LONG).show();
           }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        return view;
    }

    public class JsonTask extends AsyncTask<URL, Void, String> {

        @Override
        protected String doInBackground(URL... urls) {
            String resultado = "";
            HttpURLConnection con = null;
            try {
                // Establecer la conexión
                con = (HttpURLConnection) urls[0].openConnection();
                con.setConnectTimeout(15000);
                con.setReadTimeout(10000);

                int statusCode = con.getResponseCode();

                if (statusCode != 200) {
                    System.out.println("ERROR ESTATUS CODE: "   String.valueOf(statusCode));
                } else {
                    // Parsear el flujo con formato JSON
                    InputStream in = new BufferedInputStream(con.getInputStream());
                    resultado = convertStreamToString(in);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }

            return resultado;
        }

        protected void onPreExecute() {
            pdLoading.setMessage("tCargando información...");
            pdLoading.show();
        }

        @Override
        protected void onPostExecute(String resultado) {
            pdLoading.dismiss();
            try {
                JSONObject respuesta = new JSONObject(resultado);
                JSONArray datos = respuesta.getJSONArray("datos");

                for(int i=0;i<datos.length();i  ){

                    JSONObject clase = datos.getJSONObject(i);

                    TableRow row = new TableRow(view.getContext());
                    TextView text = new TextView(view.getContext());  text.setText(clase.getString("one"));  text.setPadding(4,2,4,2);
                    TextView text2 = new TextView(view.getContext()); text2.setText(clase.getString("two")); text2.setPadding(4,2,4,2);
                    TextView text3 = new TextView(view.getContext()); text3.setText(clase.getString("three"));    text3.setPadding(4,2,4,2);
                    TextView text4 = new TextView(view.getContext()); text4.setText(clase.getString("four"));     text4.setPadding(4,2,4,2);
                    TextView text5 = new TextView(view.getContext()); text5.setText(clase.getString("five")); text5.setPadding(4,2,4,2);
                    TextView text6 = new TextView(view.getContext()); text6.setText(clase.getString("six")); text6.setPadding(4,2,4,2);
                    TextView text7 = new TextView(view.getContext()); text7.setText(clase.getString("seven")); text7.setPadding(4,2,4,2);
                    TextView text8 = new TextView(view.getContext()); text8.setText(clase.getString("eight")); text8.setPadding(4,2,4,2);
                    TextView text9 = new TextView(view.getContext()); text9.setText(clase.getString("nine")); text9.setPadding(4,2,4,2);
                    TextView text0 = new TextView(view.getContext()); text0.setText(clase.getString("ten")); text0.setPadding(4,2,4,2);
                    row.addView(text);
                    row.addView(text2);
                    row.addView(text3);
                    row.addView(text4);
                    row.addView(text5);
                    row.addView(text6);
                    row.addView(text7);
                    row.addView(text8);
                    row.addView(text9);
                    row.addView(text0);

                    MainLayoutDatos.addView(row);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return ScreenSlidePageFragment.create(position);
        }

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

}
  

этот класс раздувает следующий XML «R.макет.fragment_clases»

 <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"
    tools:context="es.redhidrosurmedioambiente.saihredhidrosur.EmbalsesFragment"
    android:baselineAligned="false">


    <TabHost
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/tabHostEmbalses"
        android:layout_gravity="center_horizontal">

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

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:clickable="true"
                android:tabStripEnabled="true"></TabWidget>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <HorizontalScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@ id/pestanaDatosEmb" />

                <ScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@ id/pestanaGrafEmb">

                    <android.support.v4.view.ViewPager
                        xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@ id/pager"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />

                </ScrollView>

            </FrameLayout>
        </LinearLayout>
    </TabHost>


</LinearLayout>
  

в этом макете есть 2 вкладки, первая работает корректно, она показывает мне таблицу с моей информацией, во вторую я попытался поместить viewpager. Когда я на второй вкладке, мне нужно показать viewpager внутри этой вкладки. Проблема в том, что viewpager не работает, когда я переключаюсь на вторую вкладку, ошибок нет, но они ничего не показывают. Я думаю, что я выполнил все шаги в некоторых сведениях, которые я нашел в Google здесь https://developer.android.com/training/animation/screen-slide.html
Для получения дополнительной информации я поместил свой ScreenSliderPageFragment:

 import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class ScreenSlidePageFragment extends Fragment {
    /**
     * The argument key for the page number this fragment represents.
     */
    public static final String ARG_PAGE = "page";

    /**
     * The fragment's page number, which is set to the argument value for {@link #ARG_PAGE}.
     */
    private int mPageNumber;

    /**
     * Factory method for this fragment class. Constructs a new fragment for the given page number.
     */
    public static ScreenSlidePageFragment create(int pageNumber) {
        ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public ScreenSlidePageFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageNumber = getArguments().getInt(ARG_PAGE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout containing a title and body text.
        ViewGroup rootView = (ViewGroup) inflater
                .inflate(R.layout.test, container, false);

        return rootView;
    }

    /**
     * Returns the page number represented by this fragment object.
     */
    public int getPageNumber() {
        return mPageNumber;
    }
}
  

и я помещаю файл макета, который я использую для содержимого фрагмента «R.layout.test»

 <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@ id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView style="?android:textAppearanceMedium"
        android:padding="16dp"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/testString" />
</ScrollView>
  

Что мне нужно сделать, чтобы этот viewpager работал?

Комментарии:

1. используйте tablayout вместо tabhost 🙂

Ответ №1:

наконец я решил проблему. Я изменил это:

 <ScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@ id/pestanaGrafEmb">

                    <android.support.v4.view.ViewPager
                        xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@ id/pager"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />

                </ScrollView>
  

для этого:

 <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@ id/pestanaGrafEmb">

                <android.support.v4.view.ViewPager
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@ id/pager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

            </LinearLayout>