无法在同一活动中将片段A替换为片段B

时间:2015-09-05 19:25:02

标签: java android android-layout android-fragments android-activity

我的应用程序有一个主要活动,其中包含线性布局,线性布局显示一个包含按钮和文本视图的列表。我想点击Fragment A的List of List视图然后它应该用片段B替换片段A.

现在我可以点击片段A列表视图的按钮但是(它没有显示片段B)它显示Android没有响应。我已经完成了调试,并且在为片段B提交事务时遇到错误。其他代码段工作正常。

请帮我解释为什么我收到此错误 完整代码在

之下

主要活动代码

public class MainActivity extends Activity {

FrameLayout frameLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("Async","On Create");

    frameLayout = (FrameLayout) findViewById(R.id.fragment_Container);
    InstallFragmetA();
}

protected void InstallFragmetA()
{
    FragmentA fragmentA = new FragmentA();
    FragmentManager manager= getFragmentManager();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_Container,fragmentA,"A");
    transaction.commit();
}

protected void InstallFragmetB()
{
    FragmentB fragmentB = new FragmentB();
    FragmentManager manager= getFragmentManager();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_Container,fragmentB,"B");
  transaction.commit();
}
protected void RemoveFragmetA()
{

    Log.d("Async","In Remove Fragment A");
    FragmentB fragmentB = new FragmentB();
    Log.d("Async","Fragment b initializeed");
   // FragmentManager manager= getFragmentManager();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    Log.d("Async","Begin fragment transaction");
    FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("A");
   // fragmentA.onDestroy();
  //  fragmentA.onDestroyView();
    transaction.replace(R.id.fragment_Container, fragmentB, "B");
    Log.d("Async", "Fragment  A replaced");
//  transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    Log.d("Async","Fragment Failed");
//  transaction.addToBackStack(null);
    transaction.commit();
    Log.d("Async","Transaction Commit");

}

片段代码

public class FragmentA extends Fragment  {
MainActivity mainActivity= null;
TextView textView=null;
String[] friendList= null;
public FragmentA()
{
    mainActivity = new MainActivity();
}
//Activity activity= null;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // this.activity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("Async","On Create");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d("Async","On Create view");
    return inflater.inflate(R.layout.fragmenta,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    textView = (TextView) getActivity().findViewById(R.id.textView);
    ListView list = (ListView) getActivity().findViewById(R.id.listView);
    Log.d("Async","Array is "+getResources().getStringArray(R.array.FriendsList));
    friendList = getResources().getStringArray(R.array.FriendsList);
    Log.d("Async","Array is "+friendList[0]);
    textView.setText(friendList[0]);
    //   ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.FriendsList,R.layout.text);

    AdapterClass adapterClass = new AdapterClass(getActivity(),friendList,mainActivity);
    list.setAdapter(adapterClass);
    list.setItemsCanFocus(true);
    list.setFocusable(true);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override


        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d("Async","A");
            Toast.makeText(getActivity(),"Hello "+position,Toast.LENGTH_LONG).show();

        }
    });
    Log.d("Async","On Activity Created");
}

}

我用于片段A的适配器类

public class AdapterClass extends ArrayAdapter {
Button btn;
int counter=0;
Context c=null;
String[] friendList= null;
LayoutInflater l;
MainActivity mainActivity = null;
public AdapterClass(Context c, String[] friendList, MainActivity mainActivity) {
   super(c,R.layout.a,R.id.textView3,friendList);
   l  = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
   Log.d("Async","counter is ");
   this.c=c;
   this.friendList = friendList;
   this.mainActivity = mainActivity;

}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Log.d("Async","getView is "+position);
    Log.d("Async","counter is "+counter);
    View row = convertView;
    Myholder holder = null;
    if(row == null)
    {
        Log.d("Async","Row is Null");
       row  = l.inflate(R.layout.a, parent,false);
        holder = new Myholder(row);
        row.setTag(holder);
        Log.d("Async","Row Set tag");
    }
    else
    {
        Log.d("Async","Row is not null");
        holder = (Myholder) row.getTag();
        Log.d("Async","Holder not tag");
    }
   holder.btn.setText(friendList[position]);
   holder.text.setText(friendList[position]);
   holder.btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("Async","Button Clicked "+friendList[position]);
            Toast.makeText(c,"Button clicked "+friendList[position],Toast.LENGTH_LONG).show();

           mainActivity.RemoveFragmetA();
        }
    });
    return row;
}

}

片段B代码

public class FragmentB extends Fragment {
public void onAttach(Activity activity) {
    super.onAttach(activity);
    // this.activity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("Async", " Fragment B On Create");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d("Async"," Fragment B On Create view");
    return inflater.inflate(R.layout.fragmentb,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

}

activity_main.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="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/mainActivity"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
    android:layout_width="fill_parent"
    android:id="@+id/fragment_Container"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"></FrameLayout>

fragmenta.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="@+id/linearLayouts"
android:layout_height="match_parent">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#2233"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Small Text"
    android:id="@+id/textView" />
<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView" />

fragmentb.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#2233"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Small Text"
    android:id="@+id/textView" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView1" />

我越来越吵了。

E/AndroidRuntime(1021):     java.lang.IllegalStateException: Activity has been destroyed
E/AndroidRuntime(1021):     at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
E/AndroidRuntime(1021):     at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
E/AndroidRuntime(1021):     at android.app.BackStackRecord.commit(BackStackRecord.java:574)
E/AndroidRuntime(1021):     at com.example.bathla.lab5_asynctasklabtest.MainActivity.InstallFragmetB(MainActivity.java:38)
E/AndroidRuntime(1021):     at com.example.bathla.lab5_asynctasklabtest.AdapterClass$1.onClick(AdapterClass.java:64)
E/AndroidRuntime(1021):     at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(1021):     at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(1021):     at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(1021):     at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(1021):     at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1021):     at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(1021):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1021):     at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(1021):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(1021):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(1021):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

<强> MainActivity

public class MainActivity extends Activity implements FragmentAListener
{
    private FragmentA fragmentA;
    private FragmentB fragmentB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentA = (FragmentA) getFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
        if (savedInstanceState == null) {
            fragmentA = new FragmentA();
            replaceToFragment(fragmentA, false);
        }
    }

    @Override
    public void onListItemButtonClicked(String itemName) {
        fragmentB = new FragmentB();
        Bundle bundle = new Bundle();
        bundle.putString(FragmentB.ITEM_NAME_KEY, itemName);
        fragmentB.setArguments(bundle);
        replaceToFragment(fragmentB, true);
    }

    public void replaceToFragment(Fragment fragment, boolean addToBackStack) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
        if (addToBackStack) {
            transaction.addToBackStack(fragment.getClass().getSimpleName());
        }
        transaction.commit();
    }
}

<强> FragmentA

public class FragmentA extends Fragment
{
    private String[] friendList;
    private FragmentAListener listener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (!(activity instanceof FragmentAListener)) {
            throw new RuntimeException("Activity must implements FragmentAListener");
        }
        listener = (FragmentAListener) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmenta, container, false);
        TextView textView = (TextView) view.findViewById(R.id.textView);
        ListView listView = (ListView) view.findViewById(R.id.listView);
        friendList = getResources().getStringArray(R.array.FriendsList);
        textView.setText(friendList[0]);
        AdapterClass adapterClass = new AdapterClass(inflater.getContext(), friendList, listener);
        listView.setAdapter(adapterClass);
        listView.setOnItemClickListener(itemClickListener);
        return view;
    }

    private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //TODO your code
        }
    };


    public interface FragmentAListener
    {
        void onListItemButtonClicked(String itemName);
    }
}

<强> FragmentB

public class FragmentB extends Fragment
{
    public static final String ITEM_NAME_KEY = "item_name";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmentb, container, false);
        //TODO find your views here
        TextView textView = (TextView) view.findViewById(R.id.textView);
        textView.setText("Its FragmentB. Selected item: " + getArguments().getString(ITEM_NAME_KEY));
        return view;
    }
}

<强>适配器

 public class AdapterClass extends ArrayAdapter<String>
{
    private LayoutInflater inflater;
    private FragmentAListener listener;

    public AdapterClass(Context context, String[] friendList, FragmentAListener listener) {
        super(context, 0, friendList);
        inflater = LayoutInflater.from(context);
        this.listener = listener;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        Holder holder;
        if (view == null) {
            view = inflater.inflate(R.layout.list_item, parent, false);
            holder = new Holder(view);
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }
        String itemName = getItem(position);
        holder.textView.setText(itemName);
        holder.button.setText(itemName);
        holder.button.setTag(itemName);
        return view;
    }

    private class Holder
    {
        private TextView textView;
        private Button button;

        public Holder(View row) {
            textView = (TextView) row.findViewById(R.id.textView);
            button = (Button) row.findViewById(R.id.button);
            button.setOnClickListener(onClickListener);
        }
    }

    private OnClickListener onClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v) {
            listener.onListItemButtonClicked(v.getTag().toString());
        }
    };
}

活动布局

<LinearLayout
    android:id="@+id/mainActivity"
    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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>

FragmentA布局

<LinearLayout android:id="@+id/linearLayouts"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2233"
        android:text="This is Fragment A"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

FragmentB布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2233"
        android:text="This is Fragment B"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

列出项目布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/fancy_item_fragment"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal"
    android:padding="15dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Text"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>
</LinearLayout>

答案 1 :(得分:0)

在您的activity.xml,Fragment的容器

上添加此项
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragmentcontainer">
    </FrameLayout>

这对于附加片段

    Fragment fr;
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fr = new YourFragmentToShow();
    fragmentTransaction.replace(R.id.fragmentcontainer, fr)                    
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    fragmentTransaction.commit();