简体   繁体   中英

App is laggy when switching tabs in tablayout

My app is very laggy when I switch from one tab to another tab. And its just laggy in general. I dont know what to do.This is my code. How can I speed it up?where have I gone wrong?

Main Activity

    package com.example.apple.project2;
    import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
Context mContext;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundResource(Color.TRANSPARENT);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

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

    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return true;

}


@Override
public boolean onOptionsItemSelected(MenuItem menu) {
    if(menu.getItemId() == R.id.change_city){
        showInputDialog();
    }
    return false;
}

private void showInputDialog(){

}

public void changeCity(String city){

    mContext = this;
    KeyValueDB.setCity(mContext, city);
    String s=city;



}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new ListContentFragment(), "Current");
    adapter.addFragment(new DetailsFragment(),"Current Details");
    adapter.addFragment(new CardContentFragment(), "10 Day Forecast");
    viewPager.setAdapter(adapter);
}


class ViewPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}


}

ListContentFragment.java

   package com.example.apple.project2;

  import android.content.Context;
  import android.os.Bundle;
  import android.support.v4.app.Fragment;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.TextView;

  import butterknife.BindView;
  import butterknife.ButterKnife;


  public class ListContentFragment extends Fragment {
@BindView(R.id.city_field)
TextView cityText;
@BindView(R.id.temp_field)
TextView tempText;
@BindView(R.id.humity_field)
TextView humidText;

@BindView(R.id.speed_field)
TextView speedText;
Context mContext;
ViewGroup rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = (ViewGroup) inflater
            .inflate(R.layout.item_list, container, false);
    ButterKnife.bind(this, rootView);

    mContext = getContext();
    String t = KeyValueDB.getTemp(mContext);
    double cel = Double.parseDouble(t);
    tempText.setText(String.format("%.2f", cel)+"°C");
    mContext = getContext();
    String city = KeyValueDB.getCity(mContext);
    city=city.toUpperCase();
    mContext = getContext();
    String country=KeyValueDB.getCountry(mContext);
    country=country.toUpperCase();
    cityText.setText(city+" , "+country);
    mContext = getContext();
    String humid=KeyValueDB.getHumidity(mContext);
    mContext = getContext();
    String speed=KeyValueDB.getSpeed(mContext);
    humidText.setText(humid+"%");
    speedText.setText(speed+" km/hr");
    return rootView;
}

}

DetailsFragment.java

 public class DetailsFragment extends Fragment {

public final String AppID = "ebfcac32bda131ed5a160f2757938396";
public final String BASE_URL = "http://api.openweathermap.org";

@BindView(R.id.latitudeTextView)
TextView latitudeTextView;
@BindView(R.id.longitudeTextView)
TextView longitudeTextView;
@BindView(R.id.countryTextView)
TextView countryTextView;
@BindView(R.id.descriptionTextView)
TextView descriptionTextView;
@BindView(R.id.tempTextView)
TextView tempTextView;
@BindView(R.id.humidityTextView)
TextView humidityTextView;
@BindView(R.id.tempMinTextView)
TextView tempMinTextView;
@BindView(R.id.tempMaxTextView)
TextView tempMaxTextView;
@BindView(R.id.speedTextView)
TextView speedTextView;
@BindView(R.id.nameTextView)
TextView nameTextView;

private ProgressDialog mProgressDialog;
private ViewPager mCategoriesViewPager;
private TabLayout tabLayout;
private View mViewHome;
String CITY;
View view;
Context mContext;
ViewGroup rootView;
public DetailsFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = (ViewGroup) inflater
            .inflate(R.layout.item_detail, container, false);

    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setMessage(getString(R.string.fetching_weather_info));
    mProgressDialog.setCancelable(false);
    weatherUpdate();

    FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
    fab.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.cityicon));

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Change city");
            final EditText input = new EditText(getActivity());
            input.setInputType(InputType.TYPE_CLASS_TEXT);
            builder.setView(input);
            builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    changeCity(input.getText().toString());
                }
            });
            builder.show();

        }
    });




    return rootView;
}
public void weatherUpdate(){

    ButterKnife.bind(this, rootView);


    Context mContext;
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());

    mContext = getContext();

    String city = KeyValueDB.getCity(mContext);
    CITY=city;
    Retrofit retrofit = new Retrofit
            .Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    WeatherService weatherService = retrofit.create(WeatherService.class);

    Call<WeatherInfo> weatherInfoCall = weatherService.getWeatherInfo(CITY, AppID);

    weatherInfoCall.enqueue(new Callback<WeatherInfo>() {
        @Override
        public void onResponse(Call<WeatherInfo> call, Response<WeatherInfo> response) {
            showProgressDialog(false);
            onDisplayWeatherInfo(response.body());
            showProgressDialog(false);            }

        @Override
        public void onFailure(Call<WeatherInfo> call, Throwable t) {
            showProgressDialog(false);
            Toast.makeText(getActivity(), R.string.fetching_weather_info_failure, Toast.LENGTH_SHORT).show();
        }
    });
}
private void showProgressDialog(boolean show) {
    if (show) {
        if (!mProgressDialog.isShowing()) {
            mProgressDialog.show();
        }
    } else {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}


public void changeCity(String city){
    mContext = getActivity();
    KeyValueDB.setCity(mContext, city);
    CITY=city;
    weatherUpdate();
}
double f,c;
String humid,temp,speed,countryname,cityname;
private void onDisplayWeatherInfo(WeatherInfo weatherInfo) {
    if (weatherInfo != null) {

        latitudeTextView.setText(String.valueOf(weatherInfo.coord.lat));
        latitudeTextView.setText(String.valueOf(weatherInfo.coord.lat));
        longitudeTextView.setText(String.valueOf(weatherInfo.coord.lon));

        countryTextView.setText(String.valueOf(weatherInfo.sys.country));
        descriptionTextView.setText(String.valueOf(weatherInfo.weather[0].description));
        tempTextView.setText(String.valueOf(weatherInfo.main.temp));
        temp=String.valueOf(weatherInfo.main.temp);

        humidityTextView.setText(String.valueOf(weatherInfo.main.humidity));
         humid=String.valueOf(weatherInfo.main.humidity);

        tempMinTextView.setText(String.valueOf(weatherInfo.main.temp_min));
        tempMaxTextView.setText(String.valueOf(weatherInfo.main.temp_max));
        cityname=(String.valueOf(weatherInfo.name));

         countryname=(String.valueOf(weatherInfo.sys.country));

        speedTextView.setText(String.valueOf(weatherInfo.wind.speed));
        speed=String.valueOf(weatherInfo.wind.speed);

        nameTextView.setText(String.valueOf(weatherInfo.name));
        updateUI();
    }
}
public void updateUI()
{
    f=Double.parseDouble(temp);
    c= (f-273.15);
    temp = String.valueOf(c);
    mContext=getActivity();
    KeyValueDB.setTemp(mContext, temp);
    mContext=getActivity();
    KeyValueDB.setHumidity(mContext, humid);
    mContext=getActivity();
    KeyValueDB.setCity(mContext, cityname);
    mContext=getActivity();
    KeyValueDB.setCountry(mContext, countryname);
    mContext=getActivity();
    KeyValueDB.setSpeed(mContext, speed);
}


}

You are doing a lot of things in onCreateView . So the tab is not loading before completing all these tasks. Use a separate thread (something like handler.post ) to do all the heavy tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM