如何更新片段的文本视图"连续"来自viewpageradpater?viewpager适配器是在主片段中

时间:2018-04-26 06:41:31

标签: java android android-fragments android-viewpager

我的viewpager适配器位于另一个片段中(即主片段中),即我在另一个片段中使用了viewpager。所以viewpager适配器有2个片段。

我从主片段连续获取心率值,需要将其发送到viewpager适配器。然后viewpager适配器将此值发送到片段并在此处更新textview。

//主片段是我使用更新的心率值初始化fragmentpageradapter: - ((readingdata)samplePagerAdapter).passdata(value);

使用接口更新值: -

    public interface readingdata
{
    void passdata(int value);
}

//适配器代码: -

public class SamplePagerAdapter extends FragmentStatePagerAdapter implements readingdata {

private final Random random = new Random();
private int mSize = 2;
private int heart_rate;
FragmentManager fm;
private Map<Integer, String> mFragmentTags;

public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
    super(supportFragmentManager);
    fm = supportFragmentManager;
    mFragmentTags = new HashMap<Integer, String>();
}


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


@Override
public Fragment getItem(int position) {


    Fragment f = null;

    if (position == 0) {
        f = new MyFragment().newInstance(heart_rate);
    } else if (position == 1) {
        f = new SecondFragment();
    }

    return f;
}


@Override
public Object instantiateItem(ViewGroup container, int position) {
    Object object = super.instantiateItem(container, position);
    if (object instanceof Fragment) {
        Fragment fragment = (Fragment) object;
        String tag = fragment.getTag();
        mFragmentTags.put(position, tag);
    }
    return object;
}



public Fragment getFragment(int position) {
    Fragment fragment = null;
    String tag = mFragmentTags.get(position);
    if (tag != null) {
        fragment = fm.findFragmentByTag(tag);
    }
    return fragment;
}

@Override
public void passdata(int value) {

    heart_rate=value;
}

}

//片段代码是定期更新的textview

public class MyFragment extends Fragment{

private int heart_rate;
private ArcProgress arc_progress;
private TextView tv_heartrate;
private Handler handler;
private Runnable runnable;
private View view;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveBundle) {


    view = inflater.inflate(R.layout.ecg_layout, container, false);

    handler=new Handler();
    arc_progress = (ArcProgress) view.findViewById(R.id.arc_progress);
    tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);

    handler=new Handler();

    handler.post(runnable = new Runnable() {
        @Override
        public void run() {

            MyFragment myFragment=new MyFragment();
            arc_progress.setProgress(heart_rate);
            tv_heartrate.setText(String.valueOf(heart_rate));

            handler.postDelayed(this, 1000);
        }
    });


    return view;
}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


}


public static Fragment newInstance(int heartvalue) {
    MyFragment f = new MyFragment();
    f.heart_rate = heartvalue;
    return f;
}

}

那么我应该如何在片段内连续更新textview?

3 个答案:

答案 0 :(得分:1)

在MainFragment中

private static HeartRateListener heartRateListener;
        public static void setHeartRateListener(HeartRateListener listener){
            heartRateListener = listener;
        }
public static interface HeartRateListener{
            void onHeartRate(int yourValue);
}

    // Send your continuously updated value
        heartRateListener.onHeartRate(yourValue);

在ViewPager片段中(在onViewCreated()内部)

MainFragment.setHeartRateListener(new MainFragment.HeartRateListener() {
            @Override
            public void onHeartRate(int yourValue) {
               // Update your textview with yourValue
            }
        });

答案 1 :(得分:0)

   create Method 

          public void updateScreenData(String text)
 {
                    tv_heartrate.setText(text);
   } 

   in fragment and then call this method from activity
    make sure that fragment reference is not null whenever call this method

答案 2 :(得分:0)

   Take Help from this and save reference to view you are inflating 

    package com.mtg.workapp_v2.listing.wanted.add_wanted;

    import android.content.Context;
   import android.net.Uri;
 import android.os.Bundle;
import android.support.v4.app.Fragment;
 import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
   import android.widget.EditText;
import android.widget.TextView;

  import com.mtg.classes.AddressView;
   import com.mtg.classes.ListingVisibilityLayout;
  import com.mtg.utils.CommonMethods;
   import com.mtg.workapp.R;


     public class WantedBasicInfoFragment extends Fragment implements           View.OnClickListener{

  private static final String ARG_PARAM1 = "param1";
   private static final String ARG_PARAM2 = "param2";

  View FragmentView ;
  Context myContext;

   TextView text_continue;
   EditText edit_title;
   EditText edit_description;

   private OnFragmentInteractionListener mListener;

//this is add by ahsan according to new design
  ListingVisibilityLayout listingVisibilityLayout = null;


  public WantedBasicInfoFragment() {
  }


  public static WantedBasicInfoFragment newInstance(String param1, String   param2) {
      WantedBasicInfoFragment fragment = new WantedBasicInfoFragment();
      Bundle args = new Bundle();
     args.putString(ARG_PARAM1, param1);
      args.putString(ARG_PARAM2, param2);
     fragment.setArguments(args);
    return fragment;
   }

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    FragmentView= inflater.inflate(R.layout.fragment_wanted_basic, container, false);
    init();
    return FragmentView;
}

/********************************************************************************/

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);

}

/********************************************************************************/

public void setListener(OnFragmentInteractionListener listener) {
    this.mListener = listener;
}

/********************************************************************************/

public void setInitValues()
{


}

/***********************************************************************************/

public void updateScreenData()
{


    edit_title.setText(wantedInformation.csName);
    edit_description.setText(wantedInformation.csDescription);



}

/***********************************************************************************/

public void init()
{
    myContext=getActivity();


    text_continue=(TextView) FragmentView.findViewById(R.id.text_continue);

    edit_title = (EditText) FragmentView.findViewById(R.id.edit_title);

    edit_description = (EditText) FragmentView.findViewById(R.id.edit_description);

    text_continue.setOnClickListener(this);

    edit_title.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            wantedInformation.csListingLanguage = CommonMethods.getInputLanguage(myContext);

        }

        @Override
        public void afterTextChanged(Editable s) {
            wantedInformation.csListingLanguage = CommonMethods.getInputLanguage(myContext);
        }
    });

    initVisibilitySpinner();

}

/***********************************************************************************/

public void initVisibilitySpinner()
{
    listingVisibilityLayout = new ListingVisibilityLayout(myContext);
    View visibilityView = (View)FragmentView.findViewById(R.id.id_visibility_layout);
    listingVisibilityLayout.ListingVisibilityInit(visibilityView);

}

/***********************************************************************************/
@Override
public void onClick(View view) {

    int itemID = view.getId();

    switch (itemID) {
        case R.id.text_continue:
        {
            moveToNextScreen(true);
        }

    }
}


/***********************************************************************************/

public void moveToNextScreen(boolean isContinueClicked)
{
    String csName = edit_title.getText().toString().trim();
    String csDescription = edit_description.getText().toString().trim();

    if(csName.length() <= 0 && csDescription.toString().length() <= 0)
    {
        CommonMethods.showMessageBox("",     getResources().getString(R.string.id_please_enter_name_and_description), myContext);
        return;
    }
    else if(csName.length() <= 0)
    {
        CommonMethods.showMessageBox("", getResources().getString(R.string.id_please_enter_name), myContext);
        return;
    }
    else if(csDescription.length() <= 0)
    {
        CommonMethods.showMessageBox("", getResources().getString(R.string.id_please_enter_description), myContext);
        return;
    }
    else  if(listingVisibilityLayout.selectedProfileVisibility.csOptionID.equalsIgnoreCase("-1"))
    {
        CommonMethods.showMessageBox("", getResources().getString(R.string.id_select_visibility_option_msg), myContext);
        return;
    }


    wantedInformation.csName = csName;
    wantedInformation.csDescription = csDescription;

    wantedInformation.visibilityOption = listingVisibilityLayout.selectedProfileVisibility;

    //MH: If continue clicked then continue Button listener will be called
    //MH: If only tick is clicked in Edit Mode then onUpdate listener will be called
    //MH: and data will be updated before sent to api
    //MH: The below statements are repeated in all fragments of Wanted
    if(isContinueClicked)
    mListener.continueButtonPressed(wantedInformation);
    else
        mListener.onUpdate(wantedInformation);
}

}