Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
我正在使用ViewPager,并且其中有3个片段。

我知道,当ViewPager第一次加载时,默认情况下会加载所有片段,

最小为3个片段,并且viewpager执行片段的所有生命周期方法。

我注意到的问题:


每当我滑动viewpager时,所选片段都不会再次调用其任何生命周期方法。
因此,我无法直接访问全局变量。

例如:如果我在OnCreateView()中初始化了一个首选项,则通过初始化该片段的实例并在该片段中调用方法来尝试从活动访问它时,我将获得NPE。
同样,即使在第一次加载后,onResume也不会被调用任何片段。


我想知道的是:


在onCreateView()中初始化视图和首选项后,如何访问它们?
但是对于在onCreateView()中初始化的按钮,单击它会调用Web服务,并且可以按我的要求完美地工作。


在过去的3天里,我一直坚持这些问题,并在Google上搜索了很多,但没有找到答案。

任何帮助将不胜感激。

片段代码:

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

   preferences=
    PreferenceManager.getDefaultSharedPreferences(getActivity());
    editor = preferences.edit();


    editAmt = (EditText) v.findViewById(R.id.editAmt);
    browsplan = (Button) v.findViewById(R.id.browsplan);


    Log.e("DTH onCreateView ",""+page);

    String fontpath = "fonts/OpenSans-Regular.ttf";
    Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
    fontpath);

    editCustomerid.setTypeface(tf);
    editAmt.setTypeface(tf);

    token=preferences.getString("Token","-1");
    mobileNo=preferences.getString("userMobileNo","0");



    browsplan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

          //new DTHOperator(getActivity()).execute();   HERE IT WORKS PROPERLY
        }
    });

    return v;
}

 @Override
 public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if(isVisibleToUser && isResumed()){
        new DTHOperator(getActivity()).execute();
        Toast.makeText(getActivity(),"setUserVisibleHint DTH  "
       ,Toast.LENGTH_SHORT).show();
       }
    }

  public class DTHOperator extends AsyncTask<Context, Integer, String> {
    Context ctx;

    DTHOperator(Context ctx) {
        this.ctx = ctx;
    }

    @Override
    protected String doInBackground(Context... params) {
        List<NameValuePair> telecomdata = new ArrayList<NameValuePair>();
        String result;
        Log.d("Register Activity Token", /*preferences.getString("Token", "")*/token);

        telecomdata.add(new BasicNameValuePair("mobNo", /*preferences.getString("userMobileNo", "")*/mobileNo));
        telecomdata.add(new BasicNameValuePair("requestDate", Utilities.getApiCallTimeFormat()));
        telecomdata.add(new BasicNameValuePair("reqFrom", "APP"));
        Log.v("PostParameters", "telecomdata" + telecomdata);
        if (Connectivity.checkNetwork(ctx)) {
            result = rechargeUrl.queryRESTurlONline(ctx, "/GetDTHOperatorsService", "post", telecomdata, GenericConstants.PiPay_root);
        } else {
            result = GenericConstants.NETWORKNOTFOUND;
            displayToast("The Internet Connection appears to be offline");
        }


        return result;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        MyProgress.show(ctx, "", "");
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        try {
            if (result != null) {
                if (result.equalsIgnoreCase(GenericConstants.NETWORKNOTFOUND)) {
                    MyProgress.CancelDialog();
                    Toast.makeText(ctx,"The Internet Connection appears to be offline",Toast.LENGTH_SHORT).show();
                    return;
                }
                String[] resArr = result.split("delimiter_");
                if (!resArr[0].equals("500")) {
                    MyProgress.CancelDialog();
                    Log.d("DTHOperator Response ::", result);
                    JSONArray jsonArray = null;
                    JSONObject object = new JSONObject(result);
                    jsonArray = object.getJSONArray("data");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        if (jsonArray.getJSONObject(i).has("opName")) {
                            operator.add(jsonArray.getJSONObject(i).getString("opName"));

                            Log.d("", " Question size " + operator.size());
                        }
                    }

                    if(MyProgress.isShowingProgress())
                        MyProgress.CancelDialog();

                        editAmt.setText("2000");  // NPE HERE Also setting the value

                } else {
                    MyProgress.CancelDialog();
                    displayToast("Failure");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            MyProgress.CancelDialog();
        }finally {
            if(MyProgress.isShowingProgress())
                MyProgress.CancelDialog();
        }

    }

最佳答案

您可以保留在Fragments中使用的ViewPager实例。这是一个例子:

在您的ViewPagerAdapter中定义一个SparseArray并覆盖如下方法:

SparseArray<Fragment> registeredFragments = new SparseArray<>();

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    registeredFragments.put(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    registeredFragments.remove(position);
    super.destroyItem(container, position, object);
}

public Fragment getRegisteredFragment(int position) {
    return registeredFragments.get(position);
}


并将PageChangeListener添加到您的ViewPager中:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // Here's your fragment instance
        // You can access it's methods, variables, views etc.
        YourFragment fragment =(YourFragment)yourPagerAdapter.getRegisteredFragment(position);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});


希望对您有帮助。祝好运!

编辑:

您可以公开定义“片段的视图”,也可以为视图定义getter方法,并从片段实例进行访问,例如:

public TextView mTextView;


要么

private TextView mTextVieW;
public TextView getTextView(){
   return this.mTextView;
}


您可以按如下方式访问它:

TextView textView = yourFragmentInstance.mTetxView;


要么

TextView textview = yourFragmentInstance.getTextView();

关于android - Viewpager的并发症,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39749333/

10-13 04:26