0

I have a image in the main activity and when this image is clicked i want to show the fragmentA that has a list view.

When a item of this listView is clicked i want to replace the fragmentA by the fragmentB that has a textview, and I want to show in this textview the text associated to the clicked list item.

So in main activity I have this:

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);
        }
}

Note: The toast in addText() appears with the correct text at this point, so the text of the list view is received in Activity with success.

Question: Now how to replace fragmentA with fragmentB and show the textview with the received text in the activity instead of showing the listview of the fragmentA?

Below is all the complete example.

FragmentA class:

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);
    }
}

main activity 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>

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"
    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>

fragment 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>
  • Check my answer [here](https://stackoverflow.com/a/46707510/8244632), you can use a ViewPager with two fragments, limit the scrolling by touch and just use the provided solution on a ListView's item click. The side-scrolling will give your UI a nice effect instead of replacing – Lalit Fauzdar Oct 15 '17 at 17:40

3 Answers3

0

you are placing fragment A in below function instead of fragment B

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

it should be

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

if you want to replace a fragment with another just use the same container don't create separate (R.id.containerFragmentB, R.id.containerFragmentA) container.

vikas kumar
  • 10,447
  • 2
  • 46
  • 52
0

You need to change your

 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();
}

to

 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();
}

and activity_main.xml should be

<?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>

EDIT

 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);
        }
    });

Listener

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", "");
}
}

This will solve your problem

UltimateDevil
  • 2,807
  • 2
  • 18
  • 31
  • Thanks, but its also not working, when i click in the list item it appears "app keeps stopping". I think its because the AddFragmentB or sendDataToFragmentB method. Do you know where the AddFragmentB() should be placed? –  Oct 15 '17 at 17:50
  • @JonD your data is not passing because you are passing a new instance while commiting your fragment you should pass that object – UltimateDevil Oct 15 '17 at 17:51
  • I already change new FragmentB() to just fragment but the issue continues.I notice that Im not using the AddFragmentB function so I add it on the onCreate method but I run the app the app doesent run with this method AddFragmentB on the onCreate main activity method. –  Oct 15 '17 at 17:54
  • wait i will make some changes to your code may works for you but it take som time – UltimateDevil Oct 15 '17 at 17:57
  • Thanks, but its not working. The methods AddFragmentB is not being used in your example? –  Oct 15 '17 at 18:41
  • Sorry man I have done my best without my system this may be possible i missed something – UltimateDevil Oct 15 '17 at 18:45
  • wait you dont need to use addFragmentB i have already implemented the required code in sedDataToFragmentB method – UltimateDevil Oct 15 '17 at 18:51
0

This is how you will achieve the required task. make chnages to your class accordingly below. 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>
vikas kumar
  • 10,447
  • 2
  • 46
  • 52