Вызвать фрагмент из фрагмента
У меня есть действие с кнопкой на нем, и когда клик я вызываю фрагмент с другой кнопкой на фрагменте. но при нажатии на кнопку фрагмента я не могу вызвать второй фрагмент. это мой источник, довольно простой:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn_click"
android:text="Call Fragment"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:onClick="onClick"
/>
</LinearLayout>
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >
<TextView
android:id="@+id/fragment1"
android:text="Fragment 1"
android:textSize="25sp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="@+id/btn_frag2"
android:text="Call Fragment 2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >
<TextView
android:id="@+id/fragment2"
android:text="Fragment 2"
android:textSize="25sp"
android:gravity="center_vertical|center_horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View v) {
Fragment1 fragment1 = new Fragment1();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment1);
fragmentTransaction.commit();
}
}
Fragment1.java
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
}
public void onClick2(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
}
Fragment2.java
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
}
}
что не так в моем коде?
Ответы
Ответ 1
Теперь я думаю, что вложенность фрагментов доступна только для обновления флагов обратной компоновки
теперь позволяет вникнуть в проблему сам.
public void onClick2(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
Я думаю, что R.id.fragment1
принадлежит TextView
, который не является хорошим местом для включения дочерних представлений, потому что его не a ViewGroup
, вы можете удалить TextView
из xml и заменить его на LinearLayout
скажем, и это сработает, если не скажешь, какая ошибка.
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/fragment1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="@+id/btn_frag2"
android:text="Call Fragment 2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Обновить для ошибки в комментарии
public class Fragment1 extends Fragment implements OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
return v;
}
public void onClick(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Ответ 2
Если вы хотите заменить весь фрагмент 1 на Fragment2, вам нужно сделать это внутри MainActivity, используя:
Fragment1 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.commit();
Просто поместите этот код внутри метода в MainActivity, затем вызовите этот метод из Fragment1.
Ответ 3
Это мой ответ, который решил ту же проблему. Fragment2.java - это класс фрагмента, который содержит макет фрагмента2.xml.
public void onClick(View v) {
Fragment fragment2 = new Fragement2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Ответ 4
Я бы использовал слушателя. Фрагмент1, вызывающий слушателя (основное действие)
Ответ 5
Этот код работает для вызова метода parent_fragment из child_fragment.
ParentFragment parent = (ParentFragment) activity.getFragmentManager(). findViewById (R.id.contaniner);
parent.callMethod();
Ответ 6
Fragment fragment = new Fragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Ответ 7
Просто выполните это: getTabAt (индекс вашей вкладки)
ActionBar actionBar = getSupportActionBar();
actionBar.selectTab(actionBar.getTabAt(0));