将fragmentA替换为fragmentB问题

时间:2017-10-15 17:26:45

标签: android android-fragments

我在主活动中有一个图像,当点击此图像时,我想显示具有列表视图的fragmentA。

当单击此listView的项目时,我想用具有textview的fragmentB替换fragmentA,并且我想在此textview中显示与单击的列表项关联的文本。

所以在主要活动中我有这个:

public class MainActivity extends AppCompatActivity implements  Listener{
    private ImageView img;
    private String text;
    FragmentManager fragmentManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getFragmentManager();
        img = (ImageView) findViewById(R.id.imageView);
    }
    public void AddFragmentA(View view) {
        FragmentA fragmentA = new FragmentA();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
        transaction.commit();
    }
    public void AddFragmentB() {
        FragmentB fragment = new FragmentB();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
        transaction.commit();
    }
    @Override
    public void addText(String text) {
        this.text = text;
        Toast.makeText(this, "Text received in Activity:" +text, Toast.LENGTH_SHORT).show();
        sendDataToFragmentB();
    }

 public void sendDataToFragmentB(){

            FragmentB fragmentB = (FragmentB) fragmentManager.findFragmentByTag("fragB");
            fragmentB.addText(text);
        }
}

注意:此时,addText()中的toast显示正确的文本,因此在Activity中收到列表视图的文本并成功。

问题:现在如何将fragmentA替换为fragmentB,并在活动中显示带有接收文本的textview,而不是显示fragmentA的列表视图?

以下是完整的示例。

FragmentA类:

public class FragmentA extends Fragment{
    private ListView listItems;
    private String[] items = {
            "item1",
            "item2",
            "item3",
            "item4"
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listItems = (ListView) getView().findViewById(R.id.listviewInFragment);

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getActivity().getApplicationContext(),
                        android.R.layout.simple_list_item_1, android.R.id.text1, items);

        listItems.setAdapter(adapter);
        listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int positionCode = i;

                String clickedValue = (String) adapterView.getItemAtPosition(i);
                Listener listener = (Listener) getActivity();
                listener.addText(clickedValue);
            }
        });
    }

}

FramentB:

public class FragmentB extends Fragment {
    private TextView tv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, container, false);
        tv = (TextView) getView().findViewById(R.id.textView);
        return view;
    }
    public void addText(String text) {
        String result = text;
        tv.setText(result);
    }
}

主要活动xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/image"
        android:onClick="AddFragmentA"
        tools:layout_editor_absoluteX="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />
    <FrameLayout
        android:id="@+id/containerFragmentA"
        android:layout_width="0dp"
        android:layout_height="300dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        tools:layout_editor_absoluteY="1dp">
    </FrameLayout>

    <FrameLayout
        android:id="@+id/containerFragmentB"
        android:layout_width="0dp"
        android:layout_height="300dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        tools:layout_editor_absoluteY="1dp">
    </FrameLayout>
</android.support.constraint.ConstraintLayout>

片段xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0ff">

    <ListView
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="16dp"
        android:id="@+id/listviewInFragment"/>

</android.support.constraint.ConstraintLayout>

片段b xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff0">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="300dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
         />
</android.support.constraint.ConstraintLayout>

3 个答案:

答案 0 :(得分:0)

您将片段A放在下面的函数而不是片段B

 public void AddFragmentB() {
        FragmentB fragment = new FragmentB();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
        transaction.commit();
    }

应该是

public void AddFragmentB() {
        FragmentB fragment = new FragmentB();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.containerFragmentB, new FragmentB(), "fragB");
        transaction.commit();
    }

如果你想用另一个片段替换片段,只需使用相同的容器即可 不要创建单独的(R.id.containerFragmentB,R.id.containerFragmentA)容器。

答案 1 :(得分:0)

您需要更改

 public void AddFragmentA(View view) {
    FragmentA fragmentA = new FragmentA();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
    transaction.commit();
}
public void AddFragmentB() {
    FragmentB fragment = new FragmentB();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
    transaction.commit();
}

 public void AddFragmentA(View view) {
    FragmentA fragmentA = new FragmentA();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.container, fragmentA , "fragA");
    transaction.commit();
}
public void AddFragmentB() {
    FragmentB fragment = new FragmentB();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.container, fragment, "fragB");
    transaction.commit();
}

和activity_main.xml应为

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/image"
        android:onClick="AddFragmentList"
        tools:layout_editor_absoluteX="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="300dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        tools:layout_editor_absoluteY="1dp">
    </FrameLayout>


</android.support.constraint.ConstraintLayout>

修改

 listItems.setAdapter(adapter);
    listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int positionCode = i;

            String clickedValue = (String) adapterView.getItemAtPosition(i);
            Listener listener = (Listener) getActivity();
            listener.addText(clickedValue);
        }
    });

<强>监听

public interface IScanner {

void addText(String Text);

}

<强> MainActivity

public class MainActivity extends AppCompatActivity implements  Listener{
private ImageView img;
private String text;
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fragmentManager = getFragmentManager();
    img = (ImageView) findViewById(R.id.imageView);
}
public void AddFragmentA(View view) {
    FragmentA fragmentA = new FragmentA();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.containerFragmentA, new FragmentA(), "fragA");
    transaction.commit();
}

@Override
public void addText(String text) {
    this.text = text;
    Toast.makeText(this, "Text received in Activity:" +text, Toast.LENGTH_SHORT).show();
    sendDataToFragmentB(text);
}

 public void sendDataToFragmentB(String clickedValue){
    Bundle b = new Bundle();
    b.putString("clickedValue", clickedValue);

    FragmentB fragment = new FragmentB();
    fragment.setArguments(b);
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.add(R.id.containerFragmentB, new FragmentA(), "fragB");
    transaction.commit();
    }
 }

<强> FragmentB

public class FragmentB extends Fragment {
private TextView tv;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_b, container, false);
    tv = (TextView) getView().findViewById(R.id.textView);
    return view;
}
Bundle bundle = this.getArguments();
if (bundle != null) {
        String text = bundle.getString("clickedValue", "");
}
}

这将解决您的问题

答案 2 :(得分:0)

这是您完成所需任务的方法。 在下面相应地为您的班级制作课程。 的 MainActivity.java

public class MainActivity extends AppCompatActivity implements FragmentA.ClickListener{
    private Button button;
    public static String EXTRA_STRING = "extraString";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddFragment(FragmentA.getInstance());
            }
        });
    }
    public void AddFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.containerFragmentA, fragment).commit();
    }

    @Override
    public void onClick(String data) {
        AddFragment(FragmentB.getInstance(data));
    }
} 

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/containerFragmentA"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_editor_absoluteY="1dp"/>

    <Button
        android:id="@+id/button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_margin="8dp"
        android:layout_alignParentBottom="true"
        android:text="Add Fragment B"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

<强> FragmentA.java

public class FragmentA extends Fragment {
private ListView listItems;
private String[] items = {"item1", "item2", "item3", "item4"};
private ClickListener clickListener;

public static FragmentA getInstance() {
    return new FragmentA();
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    clickListener = (ClickListener)context;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_a, container, false);
    return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    listItems = (ListView) getView().findViewById(R.id.listviewInFragment);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, items);
    listItems.setAdapter(adapter);
    listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String clickedValue = items[i];
            clickListener.onClick(clickedValue);
        }
    });
}

public interface ClickListener{
    void onClick(String data);
}

}

<强> fragment_a.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="16dp"
        android:id="@+id/listviewInFragment"/>

</android.support.constraint.ConstraintLayout>

<强> FragmentB.java

public class FragmentB extends Fragment {
    private TextView tv;
    private String data;

    public static FragmentB getInstance(String data){
        Bundle bundle = new Bundle();
        bundle.putString(MainActivity.EXTRA_STRING,data);
        FragmentB fragmentB = new FragmentB();
        fragmentB.setArguments(bundle);
        return fragmentB;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, container, false);
        tv = view.findViewById(R.id.textView);
        data = getArguments().getString(MainActivity.EXTRA_STRING);
        addText(data);
        return view;
    }
    public void addText(String text) {
        String result = text;
        tv.setText(result);
    }
}

<强> fragment_b.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:gravity="center"
        android:textSize="24dp"
android:textAppearance="@style/TextAppearance.AppCompat.Widget.PopupMenu.Header"
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>