在主要活动中多次使用一个片段,监听器,方法

时间:2017-08-01 17:54:51

标签: android android-fragments android-activity interface android-fragmentactivity

我的布局中有一个带有搜索条的片段。我成功地在片段中添加了一个接口,并在main活动中实现了这个接口,这样我就可以在移动后读取seekbar的值。我希望在我的活动中有这个片段的第二个实例,并分别显示其搜索栏进度(值),但我不能。移动任何这些搜索栏(来自两个不同的片段)会改变主要活动中相同textview的值?这是代码。感谢您的帮助。

public class MainActivity extends AppCompatActivity implements OneIntSlideFragment.MyIntSlideListener {

TextView myTxt1, myTxt2;

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

    myTxt1 = (TextView) findViewById(R.id.textView1id);
    myTxt2 = (TextView) findViewById(R.id.textView2id);

    OneIntSlideFragment SlideFragment1 = (OneIntSlideFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentID1);
    OneIntSlideFragment SlideFragment2 = (OneIntSlideFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentID2);

}
    // this gets called by OneIntSlideFragment when Seekbar is changed
@Override
public void myIntSlideMethod(int slideValue) {
   int myNum = slideValue;
   if(myTxt1 != null){
       myTxt1.setText(String.valueOf(myNum));
   }
}
}

和片段的代码是:

public class OneIntSlideFragment extends Fragment {
@Nullable

private int mySeekBarValue;
TextView intSlideTitle, intSlideMinTxt, intSlideMaxTxt;
TextView intSlideNumTV;

MyIntSlideListener mListener;

public interface MyIntSlideListener{
    public void myIntSlideMethod (int slideValue);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if(context instanceof MyIntSlideListener)
        mListener = (MyIntSlideListener)context;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.one_int_slide_fragment, container, false);

    SeekBar mySeekBar;
    intSlideNumTV = (TextView) myView.findViewById(R.id.intSlideNumID);
    mySeekBar = (SeekBar) myView.findViewById(R.id.intSeekBarID);

    mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mySeekBarValue = progress;
            intSlideNumTV.setText(":  " + progress);

            mListener.myIntSlideMethod(mySeekBarValue);
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    return myView;
}
}

0 个答案:

没有答案