ANDROID片段无法添加或替换新片段

时间:2017-02-03 12:17:38

标签: java android xml android-fragments

我已经尝试了所有的建议。所有答案都是从活动中改变片段,但这是我的问题的不同之处。我试图将一个片段从第一个片段改为另一个片段。请帮助我。

我有一个包含动态按钮的片段。请找到图像[![在此输入图像描述] [1]] [1]

如果用户点击任何按钮,我想显示相同的堆栈车。请参见图像[![在此处输入图像说明] [2]] [2]

好的,这是我的要求。我的问题是我有一个活动,其中包含底部导航栏名称为ShowDashBoardActivity

ShowDashBoardActivity.java

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.yourname.R;
import com.yourname.fragments.DashBoardJobList;
import com.yourname.fragments.DashBoardOne;
import com.yourname.fragments.DashBoardTaskBubble;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarFragment;
import butterknife.Bind;


public class ShowDashBoardActivity extends AppCompatActivity {
    private BottomBar bottomBar;
    LinearLayout CardAspirationLayout,TextCardAspirationLayout;
    DashBoardOne _DashBoardOne;
    Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_dash_board_activity);
        context=getApplicationContext();
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
        View view =getSupportActionBar().getCustomView();

        /*ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });*/

        bottomBar = BottomBar.attach(this, savedInstanceState);
        bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
                new BottomBarFragment(DashBoardOne.newInstance("Content for Dashboard."), R.drawable.dashboard, "Dashboard"),
                new BottomBarFragment(DashBoardTaskBubble.newInstance("Content for Task."), R.drawable.task, "Task"),
                new BottomBarFragment(DashBoardJobList.newInstance("Content for Job."), R.drawable.job, "Job")
        );
        TextCardAspirationLayout=(LinearLayout) findViewById(R.id.TextCardAspirationLayout);
        bottomBar.setActiveTabColor("#C2185B");
        BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(2, "#E91E63", 4);
        unreadMessages.show();
        unreadMessages.setAnimationDuration(200);
        unreadMessages.setAutoShowAfterUnSelection(true);
        // bottomBar.useDarkTheme(true);
    }


}

show_dash_board_activity.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/slidetwo"
    xmlns:tools="http://schemas.android.com/tools" >


</FrameLayout>

导航抽屉工作正常。在DashBoardTaskBubble.java它是片段我正在绘制动态气泡以显示如图1所示。

DashBoardTaskBubble.java

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.panenviron.R;

import java.util.ArrayList;
import java.util.List; 
import static android.R.attr.tint;

public class DashBoardTaskBubble  extends Fragment {
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
    public DashBoardTaskBubble() {
}

    public static DashBoardTaskBubble newInstance(String text) {
        Bundle args = new Bundle();
        args.putString(STARTING_TEXT, text);

        DashBoardTaskBubble dashBoardTaskBubble = new DashBoardTaskBubble();
        dashBoardTaskBubble.setArguments(args);

        return dashBoardTaskBubble;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task_bubble, container, false);
        final RelativeLayout workViewLayout = (RelativeLayout)view.findViewById(R.id.workView);
        int iNumberOfButtons =  6; // no of bubble create function to fetch no of bubble from db
        // create a function to get color from db now give static
        String[] colourList = new String[] { "#ffaa00","#32CD32","#0000FF"};
        Button[] dynamicButtons = new Button[iNumberOfButtons];
        List<String> tempColouersList= new ArrayList<String>();
        for (int i = 0; i < iNumberOfButtons; i++) {
            dynamicButtons[i] = new Button(getActivity());
            dynamicButtons[i].setText("+"+i+5);
            dynamicButtons[i].setId(i);
            dynamicButtons[i].setTextSize(15.0f);
            dynamicButtons[i].setBackgroundResource(R.drawable.round_button);

            if(i==0){
                RelativeLayout.LayoutParams paramsButton =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton.setMargins(50,0,0,0);
                dynamicButtons[0].setLayoutParams(paramsButton);
                tempColouersList.add(colourList[0]);
            } else if(i==1){
                RelativeLayout.LayoutParams paramsButton2 =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton2.setMargins(700,10,0,0);
                dynamicButtons[1].setLayoutParams(paramsButton2);
                tempColouersList.add(colourList[1]);
            }  else if(i==2){
                RelativeLayout.LayoutParams paramsButton3 =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton3.setMargins(400,250,0,0);
                dynamicButtons[2].setLayoutParams(paramsButton3);
                tempColouersList.add(colourList[2]);
            } else if(i==3){
                RelativeLayout.LayoutParams paramsButton4 =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton4.setMargins(50,450,0,0);
                dynamicButtons[3].setLayoutParams(paramsButton4);
                tempColouersList.add(colourList[1]);
            } else if(i==4){
                RelativeLayout.LayoutParams paramsButton5 =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton5.setMargins(700,500,0,0);
                dynamicButtons[4].setLayoutParams(paramsButton5);
                tempColouersList.add(colourList[2]);
            }else if(i==5){
                RelativeLayout.LayoutParams paramsButton6 =
                        new RelativeLayout.LayoutParams(350,350);
                paramsButton6.setMargins(350,700,0,0);
                dynamicButtons[5].setLayoutParams(paramsButton6);
                tempColouersList.add(colourList[0]);
            }

            ColorStateList tint = new ColorStateList(new int[][]{new int[0]}, new int[]{Color.parseColor(tempColouersList.get(i)) });
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && dynamicButtons[i] instanceof AppCompatButton) {
                ((AppCompatButton) dynamicButtons[i]).setSupportBackgroundTintList(tint);
            } else {
                ViewCompat.setBackgroundTintList(dynamicButtons[i], tint);
            }
           dynamicButtons[i].setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   try {
                       Log.e("im on","button clik");

                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }


           });
            workViewLayout.addView(dynamicButtons[i]); // dynamicButtonsLinearLayout is the container of the buttons
        }
        return view;
    }

    public  void replaceFragments( ) {
        Log.e("im on","replaceFragments");
        //Fragment fragment = null;
        try {
            //fragment = (Fragment) TaskCardListShow.newInstance();
            /*TaskCardListShow nextFrag= new TaskCardListShow();
            this.getFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainer, nextFrag)
                    .addToBackStack(null)
                    .commit();*/

            FragmentManager  mFragmentManager = getFragmentManager();
            FragmentTransaction mFragmentTransaction = https://i.stack.imgur.com/J75iJ.pngmFragmentManager.beginTransaction();
            TaskCardListShow mFragment = new TaskCardListShow();
            //mFragmentTransaction.replace(R.id.fragmentContainer, mFragment);
            mFragmentTransaction.add(R.id.fragmentContainer, mFragment);
            mFragmentTransaction.addToBackStack(null);
            mFragmentTransaction.commit();
        } catch (Exception e)
        { e.printStackTrace(); }
        // Insert the fragment by replacing any existing fragment FragmentManager
        // fragmentManager = getSupportFragmentManager();
        // fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        }
}

fragment_task_bubble.xml

<LinearLayout 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:gravity="center_horizontal"
    android:orientation="vertical"
    android:background="@drawable/slidetwo">

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="12"
       android:background="@color/white">
   </LinearLayout>

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:layout_weight="88"
       android:orientation="vertical"
       android:background="@color/white">
      <TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="center"
          android:layout_marginTop="3dp"

          />
      <LinearLayout
          android:layout_width="wrap_content"
          android:layout_height="5dp"
          android:layout_gravity="center_horizontal"
          android:layout_marginBottom="20dp">
         <View
             android:layout_width="98dp"
             android:gravity="center_horizontal"
             android:layout_height="4dp"
             android:background="@android:color/holo_red_dark"
             android:id="@+id/normalViewSeparator"
             />
      </LinearLayout>

      <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:layout_weight="30"
          android:orientation="vertical"
          android:id="@+id/workView"
          android:background="@color/white">



      </RelativeLayout>

   </LinearLayout>

</LinearLayout>

气泡图也很完美。在这里我尝试添加一些功能,如用户点击按钮我想显示堆栈卡,如图片2

我正在考虑以片段形式显示任务卡。我不知道如何将一个片段导航到另一个片段。

TaskCardListShow.java FRAGMENT

package com.panenviron.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.panenviron.R;

public class TaskCardListShow extends Fragment {

    public TaskCardListShow() {
    }
    public static TaskCardListShow newInstance() {

        TaskCardListShow _TaskCardListShow = new TaskCardListShow();

        return _TaskCardListShow;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.task_card_list_show, container, false);
        Log.e("im on","TaskCardListShow");

        return view;
    }

}

task_card_list_show.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:id="@+id/fragment_task_card_list_show"
    style="@style/Animation.AppCompat.Dialog">

    <TextView
        android:text="Im on task fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_weight="1" />
</LinearLayout>

我尝试了上面的replaceFragments( )自定义功能。但它取代了片段,但它没有删除第一个片段。怎么做呢。

2 个答案:

答案 0 :(得分:1)

您正在使用支持片段(android.support.v4.app.Fragment)和本机fragmentmanager - Activity.getFragmentManager()。相反,你必须使用支持fragmentmanager - AppCompatActivity.getSupportFragmentManager()。

我真的希望android工具能够更好地处理这种恼人的情况。

答案 1 :(得分:1)

在片段内你必须调用getActivity()。getSupportFragmentManager()而不是getFragmentManager。所以你必须在片段事务中给出这样的“getActivity()。getSupportFragmentManager()。beginTransaction()”。之后你就可以像已经完成的那样更换