在RadioGroup中选择RadioButton时不更新android RadioButton文本,并从后台堆栈重新创建Fragment

时间:2014-10-17 10:47:37

标签: java android android-fragments

我有一个radiogroup,我以编程方式添加radiobuttons。这都是在onCreateView()方法中完成的,因此每次从backstack重新创建片段时都应该重做。我遇到的问题是,当我以编程方式使用RadioGroup.check(id)在开始时预先选择单选按钮时,RadioButton文本在后续调用onCreateView()方法时不再更新。有什么想法吗?

项目正在使用兼容性库(v4),如果这有任何区别。

以下是代码:

public static String x; //(x changes every time)

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

    View rootView = nflater.inflate(R.layout.right, container, false);

    RadioGroup rg = (RadioGroup) rootView.findViewById(R.id.radioGroup1);
    rg.removeAllViews();

    Log.d("Cild count", Integer.toString(rg.getChildCount()); // Always 0

    RadioButton.rb = new RadioButton(getActivity());

    // Always works first time. Does not work with 1 and 2 when fragment is recreated from back stack.
    rb.setText(x); 
    rb.setId(99099); // 1 Atbitrary int for id

    rg.addView(rb);
    rg.check(99099); // 2 Selection of radiobutton

    return rootView;
}

1 个答案:

答案 0 :(得分:1)

问题通过不使用backstack解决,而是手动处理onBackPressed。

Fragment fr = getSupportFragmentManager().getFragmentByTag("Fragment name");

@Override
public void onBackPressed() {

    if (fr != null)
    {
        getSupportFragmentManager().beginTransaction().replace(container, new PreviousFragment, "Tag").commit();
    }
    else
    {
        super.onBackPressed();
    }
}