如何更新viewpager adpater片段里面的片段文本视图?

时间:2018-04-25 11:39:42

标签: android android-fragments android-viewpager textview fragment

我需要更新textview,这是view pager adpater的片段

我在viewpager适配器中有2个片段。 和适配器本身在片段内。 主片段从MainActivity初始化。

我使用Greenrobot方法。在runtime.i上更新textview值。获取该值但UI闪烁意味着没有获得良好的UI。

所以我应该采用另一种方法,请建议我。

适配器代码: -

public class SamplePagerAdapter extends FragmentPagerAdapter {

    private final Random random = new Random();
    private int mSize = 2;
    private int heart_rate;
    FragmentManager fm;

    public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
        super(supportFragmentManager);
        fm = supportFragmentManager;

        heart_rate = heart;
    }


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


    @Override
    public Fragment getItem(int position) {


        Fragment f = null;
        if (position == 0) {
            f = new MyFragment();

        } else if (position == 1) {

            f = new SecondFragment();
        }

        return f;
    }

    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }


    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            fm.beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .addToBackStack(null)
                    .commit();
            return true;
        }
        return false;
    }

}

//code for loading main Fragment:-MeasureFragment
    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            Bundle bundle = new Bundle();
            bundle.putString("ble_address",bleAddress);
            fragment.setArguments(bundle);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container,fragment)
                    .addToBackStack(null)
                    .commit();
            return true;
        }
        return false;
    }

//还添加了度量片段代码: -

public class MeasureFragment extends Fragment implements ISmctAlgoCallback, IBleOperateCallback {

protected boolean measureSwitch = false;
private EcgAlgo ecgAlgo;
private BluetoothLeService mBluetoothLeService;
protected ProgressDialog mProgressDialog;
protected boolean isContecting = false;
private TextView btn_start;
private TextView tv_heartrate, tv_time, tv_pauseorresume;
private RelativeLayout linear, linear1;
private LinearLayout linear_pause, linear_stop;
private CountDownTimer timer;
private int count = 0;
private boolean running;
private Handler handler;
Runnable runnable;
ImageView iv_pauseorresume;
private boolean onclick = true;
private boolean isstop = false;
private String bleAddress;
View view1, view2, view3, view4, view5;
TextView tv_toolbar_title, tv_alarm_setting, tv_battery_percentage;
private int heart_rate;
SamplePagerAdapter samplePagerAdapter;
private FragmentActivity myContext;
ViewPager viewpager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {


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

    bleAddress = getArguments().getString("ble_address");
     viewpager = (ViewPager) view.findViewById(R.id.viewpager);
    CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
    btn_start = (TextView) view.findViewById(R.id.btn_start);
    linear = (RelativeLayout) view.findViewById(R.id.linear);
    linear1 = (RelativeLayout) view.findViewById(R.id.linear1);
    linear_pause = (LinearLayout) view.findViewById(R.id.linear_pause);
    linear_stop = (LinearLayout) view.findViewById(R.id.linear_stop);
    tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
    tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
    tv_alarm_setting = (TextView) view.findViewById(R.id.tv_alarm_setting);
    tv_battery_percentage = (TextView) view.findViewById(R.id.tv_battery_percentage);
    view1 = (View) view.findViewById(R.id.view1);
    view2 = (View) view.findViewById(R.id.view2);
    view3 = (View) view.findViewById(R.id.view3);
    view4 = (View) view.findViewById(R.id.view4);
    view5 = (View) view.findViewById(R.id.view5);

    iv_pauseorresume = (ImageView) view.findViewById(R.id.iv_pauseorresume);
    tv_pauseorresume = (TextView) view.findViewById(R.id.btn_pause);
    tv_time = (TextView) view.findViewById(R.id.time);
    ecgAlgo = new EcgAlgo();
    ecgAlgo.setISmctAlgoCallback(this);
    handler = new Handler();

    samplePagerAdapter = new SamplePagerAdapter(getActivity(), getChildFragmentManager(), heart_rate);
    viewpager.setAdapter(samplePagerAdapter);
    indicator.setViewPager(viewpager);
    viewpager.setCurrentItem(0);


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

            if (isstop) {
                measureSwitch = true;
                linear1.setVisibility(View.VISIBLE);
                linear.setVisibility(View.GONE);
                handler.post(runnable = new Runnable() {
                    @Override
                    public void run() {
                        int hours = count / 3600;
                        int minutes = (count % 3600) / 60;
                        int sec = count % 60;
                        String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
                        tv_time.setText(time);
                        if (running) {
                            count++;
                        }
                        handler.postDelayed(this, 1000);
                    }
                });

            } else {
                connectBle();
                running = true;
            }

        }
    });

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


            ecgAlgo.clearECGParam();
            isstop = true;
            measureSwitch = false;
            count = 0;
            handler.removeCallbacks(runnable);
            linear1.setVisibility(View.GONE);
            linear.setVisibility(View.VISIBLE);

        }
    });

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

            if (onclick) {
                iv_pauseorresume.setImageResource(R.drawable.resume1);
                tv_pauseorresume.setText("Resume");
                running = false;
                onclick = false;
            } else {
                onclick = true;
                running = true;
                iv_pauseorresume.setImageResource(R.drawable.pause);
                tv_pauseorresume.setText("Pause");

            }

        }
    });


    return view;
}


private void connectBle() {
    if (TextUtils.isEmpty(bleAddress)) {// 蓝牙地址为空
        showToast(R.string.ble_address_empty);
    } else if (mBluetoothLeService != null && !isContecting) {// 蓝牙未连接
        showDialog();
        mBluetoothLeService.connect(bleAddress);
        measureSwitch = true;

    } else if (mBluetoothLeService == null) {// 连接服务
        connectBleService();
    } else {// 其它
        disDialog();
        showToast(R.string.ble_connect_fail);
    }
}

/**
 * 连接蓝牙服务
 */
public void connectBleService() {
    Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
    getActivity().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}


@Override
public void bleData(short key, short value) {
    // TODO Auto-generated method stub
    switch (key) {
        case SmctConstant.KEY_BLE_CONNECT_STATE:// 连接状态改变
            if (SmctConstant.VALUE_BLE_CONNECTED == value) {// 已连接
                // hasReConnectCount = 0;
                //updateNotification(getString(R.string.notification_nomal));
            } else if (SmctConstant.VALUE_BLE_DISCONNECTED == value) {// 连接断开
                disDialog();
                if (isContecting) {//如果已连接   提示设备以断开连接
                    showToast(R.string.ble_connect_disconnect);
                } else {//没有连接   提示连接失败
                    //showToast(R.string.ble_connect_fail);
                }

                isContecting = false;
                //changeButtonSate(isContecting);
                //changeSwitchView(false);
            } else if (SmctConstant.VALUE_BLE_SERVICE_DISCOVERED == value) {// 发现服务
                if (mBluetoothLeService != null) {
                    mBluetoothLeService.setCharacteristic(mBluetoothLeService.getSupportedGattServices(),
                            SmctConstant.UUID_KEY_DATA_FFE2);
                }

                disDialog();
                isContecting = true;

                //changeButtonSate(isContecting);
                //changeSwitchView(false);

                showToast(R.string.ble_connect_success);
            }
            break;
        case SmctConstant.KEY_DEVICE_POWER_LEVEL:// 电量
            //refrashPowerLevel(value);
            //Log.d("power leve", "" + value);
            break;
        case SmctConstant.KEY_DEVICE_ELECTRODE_DROP:// 电极脱落
            if (measureSwitch)
                showToast("Elctrode Dropout!!!");
            break;
        case SmctConstant.KEY_ECG_DATA:// ecg数据
            // 正在测量中
            if (measureSwitch) {
                //refrashEcgData(value);
                //Log.d("Ecg data", "" + value);
                //算法计算
                ecgAlgo.addECGParam(value);
            }
            break;
        case SmctConstant.KEY_BODY_POSE:// 姿态
            if (value == SmctConstant.VALUE_POSE_WALK) {
                //refrashPose("go");

                Log.d("pose", "go");
            } else if (value == SmctConstant.VALUE_POSE_FALL_DOWN) {
                showToast("Falls!!!!!!");
                Log.d("pose", "Falls");
            } else if (value == SmctConstant.VALUE_POSE_LIE_LOW) {
                //refrashPose("Flat lay");
                Log.d("pose", "Flat lay");
            } else if (value == SmctConstant.VALUE_POSE_STAND) {
                //refrashPose("Flat lay");

                Log.d("pose", "Standing");
            } else if (value == SmctConstant.VALUE_POSE_SIDE_DECUBITUS) {
                Log.d("pose", "Standing");
            }
            break;

    }
}

@Override
public void bleData(short key, float[] value) {
    if (SmctConstant.KEY_ACC_DATA == key) {
        //refreshAccData(value);
    }
}

/**
 * 算法数据
 */
@Override
public void algoData(final int key, final int value) {
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            switch (key) {
                case SmctConstant.KEY_ALGO_HEART_RATE:// 心率
                    //tv_heartrate.setText(String.valueOf(value));
                    //arc_progress.setProgress(value);
                    //heart_rate=value;
                    // Bundle bundle = new Bundle();
                    //bundle.putInt("heart_rate", value);
                    //fragment.setArguments(bundle);

                    heart_rate = value;
                    Bundle bundle=new Bundle();
                    bundle.putInt("heart_rate",value);
                    samplePagerAdapter.getItem(0).setArguments(bundle);
                    //notifyViewPagerDataSetChanged();
                    break;
                case SmctConstant.KEY_ALGO_ARRHYTHMIA:// 心律失常
                    //tvArr.setText(formatString(R.string.arrhythmia, value));
                    break;
            }
        }
    });

}


public ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        if (!mBluetoothLeService.initialize()) {
            // LogUtil.e("smctservice", "Unable to initialize Bluetooth");
            // mHandler.sendEmptyMessage(MSG_BLE_UNINIT);
        } else {
            mBluetoothLeService.setBleOperate(MeasureFragment.this);
            connectBle();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        // LogUtil.e("smctservice", "onServiceDisconnected");
        mBluetoothLeService = null;
    }

};

private void notifyViewPagerDataSetChanged() {
    Log.d(TAG, "\nnotifyDataSetChanged()");
    samplePagerAdapter.notifyDataSetChanged();
}


protected void disDialog() {
    getActivity().runOnUiThread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                linear.setVisibility(View.GONE);
                linear1.setVisibility(View.VISIBLE);
                //new MyCountDownTimer(System.currentTimeMillis(),1000).start();


            }


            handler.post(runnable = new Runnable() {
                @Override
                public void run() {
                    int hours = count / 3600;
                    int minutes = (count % 3600) / 60;
                    int sec = count % 60;
                    String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
                    tv_time.setText(time);
                    if (running) {
                        count++;
                    }
                    handler.postDelayed(this, 1000);
                }
            });


        }
    });
}


protected void showToast(String msg) {
    ToastUtils.showToast(getActivity(), msg);
}

/**
 * 统一显示toast管理
 */
protected void showToast(int id) {
    ToastUtils.showToast(getActivity(), getResources().getString(id));
}


/**
 * 显示连接蓝牙dialog
 */
protected void showDialog() {
    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
        mProgressDialog = null;
    }

    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setMessage(getResources().getString(R.string.text_conn_ble));
    mProgressDialog.setCanceledOnTouchOutside(false);
    mProgressDialog.show();
}

}

需要更新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);

    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() {

            Log.d("heartrate", "" + heart_rate);
            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);



}

}

0 个答案:

没有答案