Фрагмент перекрытия друг с другом в Android

Я извлекаю данные в виде списка, используя фрагмент из MySql, и вот кнопка сверху, когда я нажимал на кнопку, она не заменяет фрагмент, который он накладывает один на другой, до и после нажатия на кнопку.

Вот код, из которого я извлекаю данные в формате списка, и по нажатию на кнопку я хочу открыть новый фрагмент, но с перехлестом.

public class PlayQuiz extends Fragment{

public String subject;

String myJSON;
private static final String TAG_RESULTS = "result";  
private static final String TAG_NAME = "subname";

String selcsub;
Button b1;

JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;

ListView list;
TextView ss,name;

InputStream is = null;
String res = null;
String line = null;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.play_quiz, container, false);

    list = (ListView) rootView.findViewById(R.id.listView);
    ss = (TextView) rootView.findViewById(R.id.textView1);
    b1 = (Button) rootView.findViewById(R.id.button1);

    b1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
                PlayQuizSubjectWise fragmentManager = new PlayQuizSubjectWise();//.beginTransaction();
                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.playsubjectwise, fragmentManager);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
        }
    });
}

Основной список XML-файла

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.sarvashikshan.PlayQuiz" 
android:background="#DCDCDC"
android:id="@+id/playsubjectwise">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select Subject"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="16dp" >
</ListView>

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/listView"
    android:layout_marginRight="44dp"
    android:text="Button" />
</RelativeLayout>

Вот список 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:orientation="vertical" 
android:background="#DCDCDC"
>

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

PlayQuizSubjectWise XML

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="31dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_marginLeft="35dp"
    android:layout_toRightOf="@+id/textView1"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<RadioGroup
    android:id="@+id/radioGroup1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="45dp" >

    <RadioButton
        android:id="@+id/radio0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true" />

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <RadioButton
        android:id="@+id/radio3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RadioGroup>

<Button
    android:id="@+id/button1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/radioGroup1"
    android:layout_marginTop="78dp"
    android:text="Next" />

<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:text="Finish" />

</RelativeLayout>

6 ответов

Решение

Родительский макет вашего второго фрагмента должен иметь фон.

PlayQuizSubjectWise XML

<RelativeLayout 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:background="#FFF"                                        //Here
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

Это перекрывается, потому что вы звоните fragmentTransaction.add который просто добавляет фрагмент в контейнер, сохраняя при этом все старые фрагменты видимыми.

Вместо этого используйте fragmentTransaction.replace который заменит все существующие фрагменты новым.

Вместо add использование replace

замещать

fragmentTransaction.add(R.id.playsubjectwise, fragmentManager);

с

fragmentTransaction.replace(R.id.playsubjectwise, fragmentManager);

Попробуй это

PlayQuizSubjectWise fragmentManager = new PlayQuizSubjectWise();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.playsubjectwise, fragmentManager);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Добавьте цвет фона к вашему фрагменту и сделайте фрагмент кликабельным

android:background="fff"
android:clickable="true" 

Если вы хотите использовать replace для фрагмента, ваш макет playsubjectwise не должен включать какой-либо вид.

Вы должны забрать TextView, ListView and Button на новый фрагмент, то вы можете использовать replace переключить два фрагмента.

MainList xml, просто макет, не включает никакого представления

<RelativeLayout 
    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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sarvashikshan.PlayQuiz" 
    android:background="#DCDCDC"
    android:id="@+id/playsubjectwise">

</RelativeLayout>

затем поместите эти представления в новый фрагмент как TempFragment.

для начала вы выполняете fragmentTransaction.add(R.id.playsubjectwise, TempFragment);

если вы хотите заменить на fragmentManagerвыполнитьfragmentTransaction.replace(R.id.playsubjectwise, fragmentManager);

это фальшивый код, надеюсь, вы понимаете.

Я также столкнулся с этой проблемой наложения фрагментов.

Для решения:

Просто задайте цвет фона для родительского макета во всех фрагментах, используя XML.

Например,

это файл onefragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    **android:background="#fff"**
    android:orientation="vertical">
       <!-- Fragments UI Components-->
</LinearLayout>

Итак, здесь я дал цвет фона #fff(белый цвет). так вот так надо давать цвет фона во всех фрагментах

Надеюсь, это поможет вам:)

Другие вопросы по тегам