Android FragmentTransaction提交两次

时间:2014-12-27 15:24:52

标签: android android-fragments

我是Android开发人员的新手,我正在尝试创建一个可点击的ListView。当你点击它的任何元素时,它会显示一个带有elememnt文本的片段。但它似乎不起作用,因为你不能两次提交FragmentTransaction。如果没有先提交,您就无法将片段添加到片段对位器中,因此您无法更改片段的文本=(

这是我的活动代码:

   public class MyActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final FragmentManager fManager = getFragmentManager();
        final FragmentTransaction fTransaction = fManager.beginTransaction();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        Random rand = new Random(); // Randomizer
        ArrayList Array = new ArrayList(5); // Array
        for(int i = 0; i < 8; i++)
        {
            Array.add(rand.nextInt(30));
        }
        ArrayAdapter<String> MyAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Array);
        final ListView listview = (ListView)findViewById(R.id.MyList);
        listview.setAdapter(MyAdapter);
        final MyFragment MyFrag = new MyFragment();
        fTransaction.add(R.id.FragmentContainer, MyFrag);
        fTransaction.commit();
        AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                String Selection = parent.getItemAtPosition(position).toString();
                MyFrag.SetText(Selection);
                fTransaction.remove(MyFrag);
                fTransaction.add(R.id.FragmentContainer, MyFrag);
                fTransaction.commit();
            }
        };
        listview.setOnItemClickListener(itemListener);
    }

我试图使用&#34;替换&#34;但结果是一样的...... 它说:

" java.lang.IllegalStateException: commit already called "

这是我的片段代码:

public class MyFragment extends Fragment
{
    TextView textView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View myInflatedView = inflater.inflate(R.layout.fragment_my_first, container, false);
        textView = (TextView) myInflatedView.findViewById(R.id.MyFragView);
        if (textView == null)
        {
            System.out.println("myInflatedView == null");
        }
        return inflater.inflate(R.layout.fragment_my_first, null);
    }
    @Override
    public void onAttach( Activity activity)
    {
        super.onAttach(activity);

        Toast.makeText(getActivity(), "You have attached a fragment",
                Toast.LENGTH_SHORT).show();
    }
    public void SetText(String text)
    {

        if(textView == null)
        {
            System.out.println("textView == null");
        }
        textView.setText(text);
    }
}

掏出一大堆难读代码=(

2 个答案:

答案 0 :(得分:1)

你必须发起一个新的交易,而不是使用之前的交易,因为你已经提交了它。

答案 1 :(得分:0)

好吧,您应该在FragmentTransaction内创建新的onItemClick,这将删除旧片段