简体   繁体   English

动态创建两个片段,以区分同一活动中的两个片段

[英]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. 因此,基本上我有一个MainActivity.java,FragmentA.java,activity_main.xml和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. 所以fragment.xml只是一个容器,该容器在一个框中具有3个按钮,当按下“开始”时,将显示从3开始的数字作为按钮文本。 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. 因此,当再次单击该按钮时,它将按钮文本更改为2,然后是1,然后是0,然后返回到3。所有减少数字并将按钮文本更改为该数字的逻辑都在FragmentA.java类中。 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. 最后,当单击操作栏中的添加按钮时,我将动态创建FragmentA并将其动态添加到MainActivity的activity_main.xml LinearLayout中。

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. 因此,现在当您在MainActivity的操作栏中按下添加按钮时,fragment.xml视图将正确地附加到activity_main.xml的LinearLayout中。 The problem is, only the first fragment that's appended in the LinearLayout is working (numbers decrement) when button is clicked. 问题是,单击按钮时,只有附加在LinearLayout中的第一个片段可以工作(数字递减)。 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? 我猜这是多次创建相同片段的某些ID问题? Any idea on how to fix this? 关于如何解决此问题的任何想法?

FragmentA.java 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 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 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 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 感谢:D

I am not quite sure but I think the problem is in the ContainerFragment Object 我不太确定,但我认为问题出在ContainerFragment对象中

FragmentA ContainerFragment = new Fragment();

try to change it to : 尝试将其更改为:

FragmentA ContainerFragment = new FragmentA();

if you can't pass the object fragmentTransaction.add do this: 如果您不能传递对象fragmentTransaction.add请执行以下操作:

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. 除了阿卜杜拉·阿森达(Abdullah Asendar)的答案之外,您还需要解决其他问题。

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. 并摆脱onActivityCreated替代,因为它不再执行任何特殊操作。

notice the subtle change View v = inflater.inflate(R.layout.fragment, container, false); 注意微妙的变化View v = inflater.inflate(R.layout.fragment, container, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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