Android ViewPager在页面之间滚动时非常不寻常的行为

时间:2017-07-21 19:20:55

标签: android android-fragments android-viewpager

我创建了视图寻呼机并在页面之间滚动(即片段)。当下页面内容滚动到显示屏时,当前页面的内容会粘在显示屏上。

Page1

Page 2 after scrolling

这是我的适配器:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
  private int numPages;

  public ViewPagerAdapter(FragmentManager fm, int numPages) {
    super(fm);
    this.numPages = numPages;
  }

  @Override
  public Fragment getItem(int position) {
    switch (position){
        case 0:
            return WeatherFragment.newInstance();
        case 1:
            return NewsFragment.newInstance();
        case 2:
            return CalenderFragment.newInstance();
        case 3:
            return MusicFragment.newInstance();
        default:
            return null;
    }
  }

  @Override
  public int getCount() {
      return this.numPages;
  }
}

这是我的天气碎片:

public class WeatherFragment extends Fragment {
Context mContext;
Utility utility;
private static final String TAG = "WeatherFragment";


public static WeatherFragment newInstance() {

    Bundle args = new Bundle();

    WeatherFragment fragment = new WeatherFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    utility = Utility.getInstance(getActivity());
}

ImageView weather_image;
TextView weather_temp, weather_des, weather_wind, weather_elevation, weather_humidity, weather_visibility;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.weather_layout, container, false);

    weather_image = (ImageView) root.findViewById(R.id.weather_image);
    weather_temp  = (TextView) root.findViewById(R.id.weather_temp);
    weather_des  = (TextView) root.findViewById(R.id.weather_description);
    weather_wind  = (TextView) root.findViewById(R.id.weather_wind);
    weather_elevation  = (TextView) root.findViewById(R.id.weather_elevation);
    weather_humidity  = (TextView) root.findViewById(R.id.weather_humidity);
    weather_visibility  = (TextView) root.findViewById(R.id.weather_visibility);


    getLocation();

    return root;
}

private void getLocation(){
    utility.jsonObjectRequest(Config.GET_LOCATION_URL, new VolleyCallback() {
        @Override
        public void onSuccess(JSONObject response) {
            IpLocation location = new IpLocation();
            try {
                location.setCity(response.getString("city"));
                location.setIp(response.getString("ip"));
                location.setRegion(response.getString("region"));
                location.setCountry(response.getString("country"));
                location.setLoc(response.getString("loc"));
                location.setOrg(response.getString("org"));

                getWeather(location);

            } catch (JSONException e) {
                e.printStackTrace();
                Snacky.builder().setActivty(getActivity())
                        .setText("In Valid Response")
                        .setDuration(Snacky.LENGTH_SHORT)
                        .warning();
            }
        }

        @Override
        public void onFailure(VolleyError error) {
            Snacky.builder().setActivty(getActivity())
                    .setText("No Internet Connection")
                    .setDuration(Snacky.LENGTH_SHORT)
                    .error();
        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
}

private void getWeather(IpLocation location){
    utility.jsonObjectRequest(Config.GET_WEATHER_URL_BASE + location.getLoc() + ".json", new VolleyCallback() {
        @Override
        public void onSuccess(JSONObject res) {
            Weather weather = new Weather();
            try {
                JSONObject response = res.getJSONObject("current_observation");
                JSONObject observationData = response.getJSONObject("observation_location");
                weather.setOb_full(observationData.getString("full"));
                weather.setOb_city(observationData.getString("city"));
                weather.setOb_country(observationData.getString("country"));
                weather.setOb_state(observationData.getString("state"));
                weather.setOb_lat(observationData.getString("latitude"));
                weather.setOb_long(observationData.getString("longitude"));
                weather.setOb_elevation(observationData.getString("elevation"));

                weather.setOb_time(response.getString("observation_time"));
                weather.setWeather(response.getString("weather"));
                weather.setTemp_c(response.getString("temp_c"));
                weather.setRelative_humidity(response.getString("relative_humidity"));
                weather.setWind_string(response.getString("wind_string"));
                weather.setWind_dir(response.getString("wind_dir"));
                weather.setWind_degrees(response.getString("wind_degrees"));
                weather.setWind_mph(response.getString("wind_mph"));
                weather.setWind_kph(response.getString("wind_kph"));
                weather.setPressure_in(response.getString("pressure_in"));
                weather.setPressure_mb(response.getString("pressure_mb"));
                weather.setPressure_trend(response.getString("pressure_trend"));
                weather.setDewpoint_c(response.getString("dewpoint_c"));
                weather.setHeat_index_c(response.getString("heat_index_c"));
                weather.setWindchill_c(response.getString("windchill_c"));
                weather.setWindchill_string(response.getString("windchill_string"));
                weather.setFeelslike_c(response.getString("feelslike_c"));
                weather.setVisibility_km(response.getString("visibility_km"));
                weather.setSolar_radiation(response.getString("solarradiation"));
                weather.setPrecip_today_in(response.getString("precip_today_in"));
                weather.setIcon(response.getString("icon"));
                weather.setIcon_url(response.getString("icon_url"));

                showWeatheronUI(weather);

            } catch (JSONException e) {
                e.printStackTrace();
                Snacky.builder().setActivty(getActivity())
                        .setText("In Valid Response")
                        .setDuration(Snacky.LENGTH_SHORT)
                        .warning();
            }
        }

        @Override
        public void onFailure(VolleyError error) {
            Snacky.builder().setActivty(getActivity())
                    .setText("No Internet Connection")
                    .setDuration(Snacky.LENGTH_SHORT)
                    .error();
        }
    });
}

private void showWeatheronUI(Weather weather){
    if(!this.isDetached()){
        Glide.with((Fragment)this)
                .load(weather.getIcon_url())
                .into(weather_image);

    }

    weather_des.setText(weather.getWeather());
    weather_temp.setText(weather.getTemp_c() + "˚C");
    weather_wind.setText(weather.getWind_string());
    weather_humidity.setText("Humidity: " + weather.getRelative_humidity());
    weather_visibility.setText(weather.getVisibility_km() + " Km");
    weather_elevation.setText(weather.getOb_elevation());
}
}

这是我的新闻片段:

public class NewsFragment extends Fragment {
TextView news_list;
Utility utility;


public static NewsFragment newInstance() {

    Bundle args = new Bundle();

    NewsFragment fragment = new NewsFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    utility = Utility.getInstance(getActivity());

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.news_layout, container, false);

    news_list = (TextView) root.findViewById(R.id.news_list);

    fetchNews();

    return root;
}


private void showNewsOnUI(String text){
    news_list.setText(text);
}

private void fetchNews(){
    utility.jsonObjectRequest(Config.GET_NEWS_URL, new VolleyCallback() {
        @Override
        public void onSuccess(JSONObject response) {
            try {
                JSONArray articles = response.getJSONArray("articles");

                String news_text ="";

                for(int i=0;i<articles.length();i++){
                    JSONObject article = (JSONObject) articles.get(i);
                    News newt = new News();
                    newt.setTitle(article.getString("title"));
                    newt.setAuthor(article.getString("author"));
                    newt.setDescription(article.getString("description"));
                    newt.setUrl(article.getString("url"));
                    newt.setUrlToImage(article.getString("urlToImage"));
                    newt.setPublishedOn(article.getString("publishedAt"));

                    news_text += newt.getTitle() + "\n";
                }

                showNewsOnUI(news_text);


            } catch (JSONException e) {
                e.printStackTrace();
                Snacky.builder().setActivty(getActivity())
                        .setText("Invalid Response Recieved")
                        .setDuration(Snacky.LENGTH_SHORT)
                        .error();
            }
        }

        @Override
        public void onFailure(VolleyError error) {
            Snacky.builder().setActivty(getActivity())
                    .setText("No Internet Connection")
                    .setDuration(Snacky.LENGTH_SHORT)
                    .error();
        }
    });
}
}

这是调用Adapter的MainActivity:

OnCreate(){
  ...
  mPageAdapter = new ViewPagerAdapter(getSupportFragmentManager(), NUM_PAGES); // NUM_PAGES=4
  viewPager.setAdapter(mPageAdapter);
  ...
}

如果按下应用程序切换器并选择相同的应用程序,那么它的视图似乎没问题。 这是新闻片段的样子,即View Pager。在应用切换器中选择相同的应用后:

News Fragment i.e

编辑:

这是我的style.xml文件:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textViewStyle">@style/MyTextViewStyle</item>
</style>

<style name="FullscreenTheme" parent="AppTheme">
    <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowBackground">@null</item>
    <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
    <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
</style>

<style name="MyTextViewStyle" parent="android:Widget.TextView">
    <item name="android:textColor">#f5f5f5</item>
</style>

<style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
    <item name="android:background">@color/black_overlay</item>
</style>

0 个答案:

没有答案