Android的ViewPager和TabLayout不工作快 [英] Android ViewPager and TabLayout are not working fast

查看:218
本文介绍了Android的ViewPager和TabLayout不工作快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有与 TabLayout ViewPager 嵌套的片段。每个片段都有它里面的列表视图,使他们得到召集,现在我得到的应用程序的处理速度慢的问题。我试图像凌空库一些解决方案,但它并没有为我工作。欲了解更多我张贴我的code太多,所以请指引我让它最好的。

MainTabFragment.java

 公共类MainTabFragment扩展片段{公共静态INT position_child_tab = 0,three_childs_tab_position = 0;
静态诠释计数= -1;
INT position_tab = 0;
捆绑ARGS;
MyTabLayout myTabLayout;公共MainTabFragment(){
    //必需的空公共构造
}/ **
 *使用此工厂方法来创建新实例
 *使用提供的参数,这个片段。
 *
 * @参数参数1参数1。
 * @参数参数2参数2。
 返回:片段MainTabFragment的一个新实例。
 * /
// TODO:重命名和更改类型和参数个数
公共静态的newInstance MainTabFragment(字符串参数1,字符串参数2){    返回新MainTabFragment();
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
    查看查看= inflater.inflate(R.layout.main_tab_fragment,集装箱,FALSE);
    myTabLayout =(MyTabLayout)view.findViewById(R.id.mainTabLayout);
    NonSiwpablePager寻呼机=(NonSiwpablePager)view.findViewById(R.id.pager);
    ARGS = getArguments();
    如果(参数= NULL&放大器;!&安培; args.containsKey(pos_next))
        position_tab = args.getInt(pos_next);
    如果(参数= NULL&放大器;!&安培; args.containsKey(pos_end))
        position_child_tab = args.getInt(pos_end);
    如果(position_child_tab!= 3){
        three_childs_tab_position = position_child_tab;
    }其他{
        three_childs_tab_position = 0;
    }
    ARGS =新包();
    args.putInt(pos_end,position_child_tab);
    ViewPagerAdapter mAdapter = getViewPagerAdapter();
    pager.setAdapter(mAdapter);
    pager.setOffscreenPageLimit(4);
    myTabLayout.setupWithViewPager(寻呼机);
    的for(int i = 0; I< mAdapter.getCount();我++){
        查看customView = mAdapter.getCustomeView(getActivity(),I);
        myTabLayout.getTabAt(ⅰ).setCustomView(customView);
    }
    pager.setCurrentItem(position_tab);
    返回视图。
}@覆盖
公共无效onViewCreated(查看视图,捆绑savedInstanceState){
    super.onViewCreated(查看,savedInstanceState);
    myTabLayout.getTabAt(position_tab).getCustomView()的setSelected(真)。
}私人ViewPagerAdapter getViewPagerAdapter(){
    ViewPagerAdapter mAdapter =新ViewPagerAdapter(getChildFragmentManager());
    字符串title_arr [] = {咨询,高级顾问,专家观点};
    的for(int i = 0; I< title_arr.length;我++){
        地图<弦乐,对象>地图=新的Hashtable<>();
        map.put(ViewPagerAdapter.KEY_TITLE,title_arr [I]);
        如果(我== 0){
            map.put(ViewPagerAdapter.KEY_FRAGMENT,AdvisoryPagerFragment.newInstance());
        }否则如果(ⅰ== 1){
            map.put(ViewPagerAdapter.KEY_FRAGMENT,TopAdvisoryPagerFragment.newInstance());
        }否则如果(ⅰ== 2){
            map.put(ViewPagerAdapter.KEY_FRAGMENT,ExperViewPagerFragment.newInstance());
        }
        mAdapter.addFragmentAndTitle(地图);    }
    返回mAdapter;
}公共静态类ViewPagerAdapter扩展FragmentStatePagerAdapter {
    私有静态最后弦乐KEY_TITLE =fragment_title;
    私有静态最后弦乐KEY_FRAGMENT =片段;
    布尔ABC = FALSE;
    私人诠释[] =可绘制新的INT [] {R.drawable.advisory_selector,R.drawable.top_advisors_selector,R.drawable.expertview_selector};
    私人列表<地图<弦乐,对象>>地图=新的ArrayList<>();    公共ViewPagerAdapter(FragmentManager FM){
        超(FM);
    }    公共查看getCustomeView(上下文的背景下,诠释POS){
        查看MVIEW = LayoutInflater.from(上下文).inflate(R.layout.custom_tab_view,NULL);
        TextView的mTextView =(TextView中)mView.findViewById(R.id.textView);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(),字体/ ufonts.com_cambria.ttf));
        ImageView的mImageView =(ImageView的)mView.findViewById(R.id.imageView2);
        mImageView.setTag(POS)        / *如果(计数大于0)
        {
            Toast.makeText(背景下,计为+算,Toast.LENGTH_SHORT).show();
            mImageView =(ImageView的)mImageView.getTag(0);
            mImageView.setSelected(假);
        }
        * /
        mImageView.setImageResource(可绘[POS]);
        mTextView.setText(getPageTitle(POS));
        返回MView的;
    }    公共无效addFragmentAndTitle(地图<弦乐,对象>图){
        maps.add(地图);
    }    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        回报(CharSequence的)maps.get(位置)获得(KEY_TITLE);
    }    @覆盖
    公共片段的getItem(INT位置){        回报(片段)maps.get(位置)获得(KEY_FRAGMENT);
    }    @覆盖
    公众诠释的getCount(){
        返回maps.size();
    }
}
}

之子片段 MainTabFragment 是:

AdvisoryPagerFragment.java

 公共类AdvisoryPagerFragment扩展片段{
静态字符串advisory_child_fragments [];
INT本身份识别码= 0;
捆束;
TabLayout mTab​​Layout;公共AdvisoryPagerFragment(){
    //必需的空公共构造
}/ **
 *使用此工厂方法来创建新实例
 *使用提供的参数,这个片段。
 *
 返回:片段AdvisoryPagerFragment的一个新实例。
 * /公共静态的newInstance AdvisoryPagerFragment(){
    返回新AdvisoryPagerFragment();
}@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
    查看膨胀; inflater.inflate(R.layout.fragment_app_pager,集装箱,FALSE);
    / *捆绑ARGS = getArguments();
    如果(参数= NULL&放大器;!&安培; args.containsKey(pos_end))
         本身份识别码= args.getInt(pos_end); * /
    身份识别码= MainTabFragment.position_child_tab;
    mTabLayout =(TabLayout)inflate.findViewById(R.id.fragmentTabLayout);
    advisory_child_fragments =新的String [] {公平,指数,商品,货币};
    ViewPager寻呼机=(ViewPager)inflate.findViewById(R.id.fragment_pager);
    FragmentViewPagerAdapter mPagerAdapter =新FragmentViewPagerAdapter(getChildFragmentManager());
    pager.setAdapter(mPagerAdapter);
    mTabLayout.setupWithViewPager(寻呼机);
    的for(int i = 0; I< mPagerAdapter.getCount();我++){
        查看customView = mPagerAdapter.getCustomeView(getActivity(),I);
        mTabLayout.getTabAt(ⅰ).setCustomView(customView);
    }
    pager.setCurrentItem(身份识别码);
    返回膨胀;
}@覆盖
公共无效onViewCreated(查看视图,捆绑savedInstanceState){
    super.onViewCreated(查看,savedInstanceState);
    mTabLayout.getTabAt(身份识别码).getCustomView()的setSelected(真)。
}公共静态类FragmentViewPagerAdapter扩展FragmentStatePagerAdapter {
    公共FragmentViewPagerAdapter(FragmentManager FM){
        超(FM);
    }    公共查看getCustomeView(上下文的背景下,诠释POS){
        查看MVIEW = LayoutInflater.from(上下文).inflate(R.layout.custom_view,NULL);
        TextView的mTextView =(TextView中)mView.findViewById(R.id.belowTab_textview);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(),字体/ ufonts.com_cambria.ttf));
        mTextView.setText(getPageTitle(POS));
        返回MView的;
    }    //
    @覆盖
    公共CharSequence的getPageTitle(INT位置){
        返回advisory_child_fragments [位置]
    }    @覆盖
    公共片段的getItem(INT位置){
        开关(位置){
            情况下0:
                返回新EquityFragment();
            情况1:
                返回新IndicesFragment();
            案例2:
                返回新CommodityFragment();
            案例3:
                返回新CurrencyFragment();
        }
        返回null;
    }    @覆盖
    公众诠释的getCount(){
        返回4;
    }
 }
 }

和以上 AdvisoryPagerFragment 子片段

EquityFragment.java

 公共类EquityFragment扩展android.support.v4.app.Fragment实现SearchView.OnQueryTextListener {
公共静态字符串的ImagePath = NULL;
静态的ArrayList< EquityDetails> catListDao =新的ArrayList< EquityDetails>();
静态的ArrayList< EquityDetails> catListDao1 =新的ArrayList< EquityDetails>();
静态诠释计数= 0;
静态INT COUNT1 = 0;
ListView控件列表;
查看视图。
活动的行为;
AdvisorsAdapter适配器;
TextView的empty_text;
私人布尔isViewShown = FALSE;
进度进度;公共静态的newInstance EquityFragment(){
    返回新EquityFragment();
}@覆盖
公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
    鉴于= inflater.inflate(R.layout.equity_activity,集装箱,FALSE);
    ACT = this.getActivity();
    Log.d(Callled,+计数);
    算上++;
    返回视图。
}公共无效onActivityCreated(捆绑savedInstanceState1){
    super.onActivityCreated(savedInstanceState1);
    如果(android.os.Build.VERSION.SDK_INT> 9){
        。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
        StrictMode.setThreadPolicy(政策);
    }
    名单=(ListView控件)view.findViewById(R.id.list_equity);
    setHasOptionsMenu(真);
    empty_text =(TextView中)view.findViewById(R.id.empty);
    进度=(进度)view.findViewById(R.id.progressBar);
    如果(Utils.isNetworkAvailable(getActivity())){
        如果(catListDao.size()大于0){
            适配器=新AdvisorsAdapter(动作,R.layout.custom_equity,catListDao,5);
            list.setAdapter(适配器);
        }其他{
            新主题(新的Runnable接口(){
                @覆盖
                公共无效的run(){
                    //做一些工作在这里
                    getActivity()。runOnUiThread(新的Runnable(){
                        @覆盖
                        公共无效的run(){
                            //如果(!isViewShown){
                            新FetchAllData(getActivity(),5).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            //}
                        }
                    });
                }
            })。开始();
        }
    }其他{
        CustomToast敬酒=新CustomToast(getActivity(),没有互联网连接!);
    }
 }

FetchdataClass 从服务获取数据,并添加到的ListView

 公共类FetchAllData扩展的AsyncTask<太虚,太虚,字符串> {
    ProgressDialog pDialog;
    INT typeid的;
    私人语境续;    公共FetchAllData(上下文CON,诠释typeid的){
        // TODO自动生成构造函数存根
        this.cont = CON;
        this.typeId = typeid的;
        Log.d(构造器调用,是);
    }    @覆盖
    在preExecute保护无效(){
        // TODO自动生成方法存根
        super.on preExecute();        progressBar.setVisibility(View.VISIBLE);
    }
    @覆盖
    保护字符串doInBackground(虚空...... PARAMS){
        // TODO自动生成方法存根
        返回的getString();
    }    私人字符串的getString(){
        // TODO自动生成方法存根
        URL的obj = NULL;
        HttpURLConnection类CON = NULL;
        尝试{
            OBJ =新的URL(Constants.AppBaseUrl +/ call_listing /+ typeid的);
            串的userPassword =OI+:+KL;
            串标头=基本+新的String(android.util.Base64.en code(userPassword.getBytes(),android.util.Base64.NO_WRAP));
            CON =(HttpURLConnection类)obj.openConnection();
            con.addRequestProperty(授权,标题);
            con.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            con.setRequestMethod(POST);
            //为岗位仅 - BEGIN
            con.setDoOutput(真);
            OutputStream的OS = con.getOutputStream();            os.flush();
            os.close();
            //仅适用于POST - END            INT响应code = con.getResponse code();
            如果(响应code == HttpURLConnection.HTTP_OK){//成功
                在的BufferedReader =新的BufferedReader(新的InputStreamReader(con.getInputStream()));
                串inputLine;
                StringBuffer的响应=新的StringBuffer();                而((inputLine = in.readLine())!= NULL){
                    response.append(inputLine);
                }
                附寄();
                Log.i(TAG,response.toString());
                返回response.toString();
            }其他{
                Log.i(TAG,POST请求没有工作。);
            }
        }赶上(IOException异常五){
            e.printStackTrace();
        }
        返回null;
    }
    @覆盖
    保护无效onPostExecute(字符串结果){
        // TODO自动生成方法存根
        super.onPostExecute(结果);
        如果(结果!= NULL){
            // pDialog.dismiss();
            progressBar.setVisibility(View.GONE);
            的JSONObject的JSONObject;
            尝试{
                catListDao =新的ArrayList< EquityDetails>();
                JSONObject的=新的JSONObject(结果);
                JSONArray jsonArray = jsonObject.getJSONArray(名单);                Log.d(长度,+ jsonArray.length());
                的for(int i = 0; I< jsonArray.length();我++){
                    EquityDetails allDirectory =新EquityDetails();
                    allDirectory.setEntry_value(jsonArray.getJSONObject㈠.getString(入口));
                    allDirectory.setSerial_value(jsonArray.getJSONObject(I).getString(SL));
                    allDirectory.setTg_value1(jsonArray.getJSONObject㈠.getString(tgt_1));
                    allDirectory.setTg_value2(jsonArray.getJSONObject㈠.getString(tgt_2));
                    allDirectory.setMainTitle_value(jsonArray.getJSONObject(I).getString(脚本));
                    allDirectory.setMain_subTitle_value(jsonArray.getJSONObject(I).getString(「联交所」));
                    allDirectory.setRating_value(jsonArray.getJSONObject(I).getString(等级));
                    allDirectory.setReview_value(jsonArray.getJSONObject(I).getString(审查));
                    allDirectory.setImage1(jsonArray.getJSONObject㈠.getString(advisor_image));
                    allDirectory.setPosted_by(jsonArray.getJSONObject㈠.getString(posted_by));
                    allDirectory.setImage2(jsonArray.getJSONObject㈠.getString(script_image));
                    allDirectory.setCall_id(jsonArray.getJSONObject㈠.getString(CALL_ID));
                    allDirectory.setBuy(jsonArray.getJSONObject㈠.getString(buy_sentiment));
                    allDirectory.setSell(jsonArray.getJSONObject㈠.getString(sell_sentiment));
                    allDirectory.setRecommend(jsonArray.getJSONObject(I).getString(推荐));
                    allDirectory.setPosted_date(jsonArray.getJSONObject㈠.getString(posted_date));
                    allDirectory.setExpiry_date(jsonArray.getJSONObject(I).getString(EXPIRY_DATE));
                    catListDao.add(allDirectory);
                }
                catListDao1 = catListDao;
                AB =真;
                适配器=新AdvisorsAdapter(ACT,R.layout.custom_equity,catListDao,0);
                list.setAdapter(适配器);
            }赶上(JSONException E){
                e.printStackTrace();
            }        }
        //pDialog.dismiss();
        progressBar.setVisibility(View.GONE);    }
}


解决方案

尝试设置pager.setOffscreenPageLimit(no_of_fragments或页面);

贵公司的所有任务asyctask在创建片段

There are nested fragments with TabLayout and ViewPager. Each fragment has listview inside it so they get call together and now I'm getting an issue of slow processing of app. I have tried some solutions like volley library but it didn't work for me. For more I'm posting my code too so please guide me to make it best.

MainTabFragment.java

public class MainTabFragment extends Fragment {

public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
MyTabLayout myTabLayout;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment MainTabFragment.
 */
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {

    return new MainTabFragment();
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
    myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
    NonSiwpablePager pager = (NonSiwpablePager) view.findViewById(R.id.pager);
    args = getArguments();
    if (args != null && args.containsKey("pos_next"))
        position_tab = args.getInt("pos_next");
    if (args != null && args.containsKey("pos_end"))
        position_child_tab = args.getInt("pos_end");
    if (position_child_tab != 3) {
        three_childs_tab_position = position_child_tab;
    } else {
        three_childs_tab_position = 0;
    }
    args = new Bundle();
    args.putInt("pos_end", position_child_tab);
    ViewPagerAdapter mAdapter = getViewPagerAdapter();
    pager.setAdapter(mAdapter);
    pager.setOffscreenPageLimit(4);
    myTabLayout.setupWithViewPager(pager);
    for (int i = 0; i < mAdapter.getCount(); i++) {
        View customView = mAdapter.getCustomeView(getActivity(), i);
        myTabLayout.getTabAt(i).setCustomView(customView);
    }
    pager.setCurrentItem(position_tab);
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}

private ViewPagerAdapter getViewPagerAdapter() {
    ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
    String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
    for (int i = 0; i < title_arr.length; i++) {
        Map<String, Object> map = new Hashtable<>();
        map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
        if (i == 0) {
            map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
        } else if (i == 1) {
            map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
        } else if (i == 2) {
            map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
        }
        mAdapter.addFragmentAndTitle(map);

    }
    return mAdapter;
}

public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private static final String KEY_TITLE = "fragment_title";
    private static final String KEY_FRAGMENT = "fragment";
    boolean abc = false;
    private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
    private List<Map<String, Object>> maps = new ArrayList<>();

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

    public View getCustomeView(Context context, int pos) {
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
        TextView mTextView = (TextView) mView.findViewById(R.id.textView);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
        ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
        mImageView.setTag(pos);

        /*if(count >0)
        {
            Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
            mImageView =  (ImageView) mImageView.getTag(0);
            mImageView.setSelected(false);
        }
        */
        mImageView.setImageResource(drawables[pos]);
        mTextView.setText(getPageTitle(pos));
        return mView;
    }

    public void addFragmentAndTitle(Map<String, Object> map) {
        maps.add(map);
    }

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

    @Override
    public Fragment getItem(int position) {

        return (Fragment) maps.get(position).get(KEY_FRAGMENT);
    }

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


}

Child Fragment of MainTabFragment is as :

AdvisoryPagerFragment.java

public class AdvisoryPagerFragment extends Fragment {
static String advisory_child_fragments[];
int myID = 0;
Bundle bundle;
TabLayout mTabLayout;

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

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @return A new instance of fragment AdvisoryPagerFragment.
 */

public static AdvisoryPagerFragment newInstance() {
    return new AdvisoryPagerFragment();
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View inflate = inflater.inflate(R.layout.fragment_app_pager, container, false);
    /*Bundle args = getArguments();
    if (args  != null && args.containsKey("pos_end"))
         myID = args.getInt("pos_end");*/
    myID = MainTabFragment.position_child_tab;
    mTabLayout = (TabLayout) inflate.findViewById(R.id.fragmentTabLayout);
    advisory_child_fragments = new String[]{"EQUITY", "INDICES", "COMMODITY", "CURRENCY"};
    ViewPager pager = (ViewPager) inflate.findViewById(R.id.fragment_pager);
    FragmentViewPagerAdapter mPagerAdapter = new FragmentViewPagerAdapter(getChildFragmentManager());
    pager.setAdapter(mPagerAdapter);
    mTabLayout.setupWithViewPager(pager);
    for (int i = 0; i < mPagerAdapter.getCount(); i++) {
        View customView = mPagerAdapter.getCustomeView(getActivity(), i);
        mTabLayout.getTabAt(i).setCustomView(customView);
    }
    pager.setCurrentItem(myID);
    return inflate;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mTabLayout.getTabAt(myID).getCustomView().setSelected(true);
}

public static class FragmentViewPagerAdapter extends FragmentStatePagerAdapter {
    public FragmentViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    public View getCustomeView(Context context, int pos) {
        View mView = LayoutInflater.from(context).inflate(R.layout.custom_view, null);
        TextView mTextView = (TextView) mView.findViewById(R.id.belowTab_textview);
        mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
        mTextView.setText(getPageTitle(pos));
        return mView;
    }

    //
    @Override
    public CharSequence getPageTitle(int position) {
        return advisory_child_fragments[position];
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new EquityFragment();
            case 1:
                return new IndicesFragment();
            case 2:
                return new CommodityFragment();
            case 3:
                return new CurrencyFragment();
        }
        return null;
    }

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

And the child fragment of above AdvisoryPagerFragment is

EquityFragment.java

public class EquityFragment extends android.support.v4.app.Fragment implements SearchView.OnQueryTextListener {
public static String imagepath = null;
static ArrayList<EquityDetails> catListDao = new ArrayList<EquityDetails>();
static ArrayList<EquityDetails> catListDao1 = new ArrayList<EquityDetails>();
static int count = 0;
static int count1 = 0;
ListView list;
View view;
Activity act;
AdvisorsAdapter adapter;
TextView empty_text;
private boolean isViewShown = false;
ProgressBar progressBar;

public static EquityFragment newInstance() {
    return new EquityFragment();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.equity_activity, container, false);
    act = this.getActivity();
    Log.d("Callled ", "" + count);
    count++;
    return view;
}

public void onActivityCreated(Bundle savedInstanceState1) {
    super.onActivityCreated(savedInstanceState1);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    list = (ListView) view.findViewById(R.id.list_equity);
    setHasOptionsMenu(true);
    empty_text = (TextView) view.findViewById(R.id.empty);
    progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    if (Utils.isNetworkAvailable(getActivity())) {
        if (catListDao.size() > 0) {
            adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 5);
            list.setAdapter(adapter);
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // do some work here
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //   if (!isViewShown) {
                            new FetchAllData(getActivity(), 5).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            //    }
                        }
                    });
                }
            }).start();
        }
    } else {
        CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
    }
 }

FetchdataClass which fetches the data from service and add into ListView

public class FetchAllData extends AsyncTask<Void, Void, String> {
    ProgressDialog pDialog;
    int typeId;
    private Context cont;

    public FetchAllData(Context con, int typeId) {
        // TODO Auto-generated constructor stub
        this.cont = con;
        this.typeId = typeId;
        Log.d("Constructor Called", "yes");
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        progressBar.setVisibility(View.VISIBLE);
    }


    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        return getString();
    }

    private String getString() {
        // TODO Auto-generated method stub


        URL obj = null;
        HttpURLConnection con = null;
        try {
            obj = new URL(Constants.AppBaseUrl + "/call_listing/" + typeId);
            String userPassword = "oi" + ":" + "kl";
            String header = "Basic " + new String(android.util.Base64.encode(userPassword.getBytes(), android.util.Base64.NO_WRAP));
            con = (HttpURLConnection) obj.openConnection();
            con.addRequestProperty("Authorization", header);
            con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            con.setRequestMethod("POST");


            // For POST only - BEGIN
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();

            os.flush();
            os.close();
            // For POST only - END

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Log.i("TAG", response.toString());
                return response.toString();


            } else {
                Log.i("TAG", "POST request did not work.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);


        if (result != null) {
            //    pDialog.dismiss();
            progressBar.setVisibility(View.GONE);
            JSONObject jsonObject;
            try {
                catListDao = new ArrayList<EquityDetails>();
                jsonObject = new JSONObject(result);
                JSONArray jsonArray = jsonObject.getJSONArray("list");

                Log.d("Length ", "" + jsonArray.length());
                for (int i = 0; i < jsonArray.length(); i++) {
                    EquityDetails allDirectory = new EquityDetails();
                    allDirectory.setEntry_value(jsonArray.getJSONObject(i).getString("entry"));
                    allDirectory.setSerial_value(jsonArray.getJSONObject(i).getString("sl"));
                    allDirectory.setTg_value1(jsonArray.getJSONObject(i).getString("tgt_1"));
                    allDirectory.setTg_value2(jsonArray.getJSONObject(i).getString("tgt_2"));
                    allDirectory.setMainTitle_value(jsonArray.getJSONObject(i).getString("script"));
                    allDirectory.setMain_subTitle_value(jsonArray.getJSONObject(i).getString("exchange"));
                    allDirectory.setRating_value(jsonArray.getJSONObject(i).getString("rating"));
                    allDirectory.setReview_value(jsonArray.getJSONObject(i).getString("review"));
                    allDirectory.setImage1(jsonArray.getJSONObject(i).getString("advisor_image"));
                    allDirectory.setPosted_by(jsonArray.getJSONObject(i).getString("posted_by"));
                    allDirectory.setImage2(jsonArray.getJSONObject(i).getString("script_image"));
                    allDirectory.setCall_id(jsonArray.getJSONObject(i).getString("call_id"));
                    allDirectory.setBuy(jsonArray.getJSONObject(i).getString("buy_sentiment"));
                    allDirectory.setSell(jsonArray.getJSONObject(i).getString("sell_sentiment"));
                    allDirectory.setRecommend(jsonArray.getJSONObject(i).getString("recommendation"));
                    allDirectory.setPosted_date(jsonArray.getJSONObject(i).getString("posted_date"));
                    allDirectory.setExpiry_date(jsonArray.getJSONObject(i).getString("expiry_date"));
                    catListDao.add(allDirectory);
                }
                catListDao1 = catListDao;
                ab = true;
                adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 0);
                list.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        //pDialog.dismiss();
        progressBar.setVisibility(View.GONE);

    }


}

解决方案

try to set pager.setOffscreenPageLimit(no_of_fragments or pages);

Do all your task in asyctask on creation of fragments

这篇关于Android的ViewPager和TabLayout不工作快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆