简体   繁体   中英

Dynamically creating two fragments that differentiate between the two in same activities

So I've searched for hours trying to find an answer to this specific problem I'm having with no luck. Would be great if someone can help me out.

So essentially I have a MainActivity.java, FragmentA.java, activity_main.xml, and fragment.xml. So what fragment.xml has is just a container that have 3 buttons in a box that when pressed Start showing a number starting from 3 as the buttons text. So when you click the button again, it changes the button text to 2 and then 1 and then 0 and then back to 3. All the logic that decrements the numbers and changes the button text to that number is in the FragmentA.java class. All that's logic is working, I've tested it. Finally I create and add FragmentA dynamically to MainActivity's activity_main.xml LinearLayout when an add button in actionbar is clicked.

So now when you press the add button in the actionbar in MainActivity, the fragment.xml view is correctly appended to activity_main.xml's LinearLayout. The problem is, only the first fragment that's appended in the LinearLayout is working (numbers decrement) when button is clicked. The other fragment copies are not working or doing anything, but just showing. So the buttons decrement logic is only working for the first added view. Why is that? I thought the point of fragments was to elimanate duplication. I'm guessing this is some ID issue with the same fragment being created multiple times? Any idea on how to fix this?

FragmentA.java

Button b1, b2, b3;
int[] mCounter = {3, 3, 3};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment, null);
    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    b1 = (Button) getActivity().findViewById(R.id.button);
    b1.setOnClickListener(this);
    b2 = (Button) getActivity().findViewById(R.id.button2);
    b2.setOnClickListener(this);
    b3 = (Button) getActivity().findViewById(R.id.button3);
    b3.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.button:
            b1.setText(Integer.toString(mCounter[0]));
            decrementCounterByButtonPosition(0);
            break;
        case R.id.button2:
            b2.setText(Integer.toString(mCounter[1]));
            decrementCounterByButtonPosition(1);
            break;
        case R.id.button3:
            b3.setText(Integer.toString(mCounter[2]));
            decrementCounterByButtonPosition(2);
            break;
    }
}

public void decrementCounterByButtonPosition(int counterId) {
    if (mCounter[counterId] != 0) {
        mCounter[counterId]--;
    } else {
        mCounter[counterId] = 3;
    }
}

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {        
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_add_exercise) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        FragmentA ContainerFragment = new FragmentA();
            fragmentTransaction.add(R.id.container, ContainerFragment, "HELLO");
        fragmentTransaction.commit();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

activity_main.xml

<ScrollView
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#1FDA9A">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical"
    android:id="@+id/container">
</LinearLayout>

fragment.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="wrap_content"
android:paddingTop="0dp"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/globalContainer"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#fff"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:backgroundTint="#333"
        android:gravity="center_vertical|center_horizontal">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:maxWidth="10dp"
            android:maxHeight="10dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button2"
            android:maxWidth="10dp"
            android:maxHeight="10dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button3"
            android:maxWidth="10dp"
            android:maxHeight="10dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp" />
    </LinearLayout>
</LinearLayout>

Any help appreciated. Thanks :D

I am not quite sure but I think the problem is in the ContainerFragment Object

FragmentA ContainerFragment = new Fragment();

try to change it to :

FragmentA ContainerFragment = new FragmentA();

if you can't pass the object fragmentTransaction.add do this:

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = 
                                                       fragmentManager.beginTransaction();

I hope this helps.

In addition to Abdullah Asendar's answer, you have another thing to fix.

The problem is with the way you are getting your views.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    b1 = (Button) getActivity().findViewById(R.id.button);
    b1.setOnClickListener(this);
    b2 = (Button) getActivity().findViewById(R.id.button2);
    b2.setOnClickListener(this);
    b3 = (Button) getActivity().findViewById(R.id.button3);
    b3.setOnClickListener(this);
}

This finds views from the Activity, not from your fragment.

The correct way to do this is:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment, container, false);
    b1 = (Button) v.findViewById(R.id.button);
    b1.setOnClickListener(this);
    b2 = (Button) v.findViewById(R.id.button2);
    b2.setOnClickListener(this);
    b3 = (Button) v.findViewById(R.id.button3);
    b3.setOnClickListener(this);
    return v;
}

and get rid of your onActivityCreated override because it no longer does anything special.

notice the subtle change View v = inflater.inflate(R.layout.fragment, container, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM