Reputation: 423
I'm new to Android Developing and i'm trying to create a clickable ListView. And when you click on any element of it, it shows a fragment with the text from elememnt. But it doesn't seem to work becouse you can't commit FragmentTransaction twice. And without first commiting you can't add a fragment to fragment contrainer and therefore you can't change the text of Fragment=(
Here's my Activity Code:
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);
}
I've tried to use "replace" but the result was the same... It says:
" java.lang.IllegalStateException: commit already called "
Here is my fragment code:
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);
}
}
Sry for a huge pack of hard-reading code=(
Upvotes: 0
Views: 1822
Reputation: 12977
well, you should create new FragmentTransaction
inside the onItemClick
which will remove the old fragment
Upvotes: 0
Reputation: 534
You have to initiate a new transaction, not use the previous because you have already commit it.
Upvotes: 1