从活动更新片段

时间:2014-06-12 01:49:42

标签: android-fragments

我的活动有两个片段。 Activity接收两个片段的广播事件。 一个片段具有图像按钮和文本视图。单击图像按钮时,会向服务器发送一个事件,服务器将通过直播事件进行响应。

我们在活动中收到响应,我需要更新片段的UI(图像按钮需要用其他图像更改)

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

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

        return view;
    }

    public void updateUI(View view){

        String lockName;
        final String lockState;
        final boolean state;

        final ImageButton singleLockImage = (ImageButton)view.findViewById(R.id.single_lock_image);
        final TextView lockNameText = (TextView)view.findViewById(R.id.single_lock_name);
        final TextView lockStateText = (TextView)view.findViewById(R.id.single_lock_state);
        final ProgressBar progress = (ProgressBar)view.findViewById(R.id.singleLockProgress);

            doorLock = LockState.getValue();

        lockName = doorLock.getName();
        if (doorLock.isLocked()) {
            lockState = getActivity().getString(R.string.door_locks_locked);
            singleLockImage.setImageResource(R.drawable.doorlocks_single_locked);
            state = true;
        } else {
            lockState = getActivity().getString(R.string.door_locks_unlocked);
            singleLockImage.setImageResource(R.drawable.doorlocks_single_unlocked);
            state = false;
        }

        lockNameText.setText(lockName);
        lockStateText.setText(lockState);
        singleLockImage.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        getActivity().changeState(state);
                    }
                }
        );

    }

我想调用updateUI,它会在Activity中收到广播事件后从缓存中获取新状态,但我不知道如何传递(查看)

1 个答案:

答案 0 :(得分:0)

改为使用FragmentActivity。

FragmentActivity中的

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

        // Create an instance of ExampleFragment
        TestFragment0 firstFragment = new TestFragment0();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, firstFragment).commit();
}
片段的FragmentActivity中的

TestFragment0 firstFragment0 = new TestFragment0();
firstFragment0.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,firstFragment0).commit();