片段没有被取代

时间:2013-11-16 07:28:30

标签: android android-fragments

我有一个带有两个片段的活动,左边的一个是静态的,并在GridView中显示类别的名称;我在右侧有一个framelayout,可以根据需要保存动态片段。最初它显示一个片段TopicListFragment(一个带有类别主题的listView),然后单击CREATE类别按钮(这在左侧的GridView上方)右侧的TopicListFragment被另一个片段FormCreateCategoryFragment替换。现在,如果我单击左侧gridView中的任何类别,则此FormCreateCategoryFragment应再次被TopicListFragment替换,以显示所单击类别的主题,但应用程序崩溃时出现以下错误---

=============================================== ======================================

    01-02 11:11:33.564: W/dalvikvm(2466): threadid=1: thread exiting with uncaught exception (group=0x409f41f8)
01-02 11:11:33.574: E/AndroidRuntime(2466): FATAL EXCEPTION: main
01-02 11:11:33.574: E/AndroidRuntime(2466): java.lang.ClassCastException: com.gitanjal.together.view.FormCreateCategoryFragment cannot be cast to com.gitanjal.together.view.TopicListFragment
01-02 11:11:33.574: E/AndroidRuntime(2466):     at com.gitanjal.together.view.CategoryListFragment.showTopics(CategoryListFragment.java:145)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at com.gitanjal.together.view.CategoryListFragment.access$1(CategoryListFragment.java:139)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at com.gitanjal.together.view.CategoryListFragment$2.onItemClick(CategoryListFragment.java:93)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.widget.AdapterView.performItemClick(AdapterView.java:292)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.widget.AbsListView$1.run(AbsListView.java:3168)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.os.Handler.handleCallback(Handler.java:605)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.os.Looper.loop(Looper.java:137)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at java.lang.reflect.Method.invokeNative(Native Method)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at java.lang.reflect.Method.invoke(Method.java:511)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-02 11:11:33.574: E/AndroidRuntime(2466):     at dalvik.system.NativeStart.main(Native Method)

=============================================== ===========================================

我的代码是 -

     import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.Toast;

import com.gitanjal.together.request.RequestHandler;

/*
 * CLASS:CategoryListFragment 
 * PURPOSE:This is a fragment to display the list of categories
 * */
public class CategoryListFragment extends Fragment {

    RequestHandler newRequest = new RequestHandler(); // Create an object to
                                                        // make the requests to
                                                        // RequestHandler
    Context contextParent = this.getActivity();         ///context of the parent activity
    int noOfCategories=0;
    //String responseArray[];
    Button btnCreateCategory;
    boolean mDualPane;
    int mCurCheckPosition = 0; 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        System.out.println("Category list activity extends fragment");              

        newRequest.requestGetCategories(contextParent,this);                                //Make the request
        return inflater.inflate(R.layout.category_grids, null, false);      
    }
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        //Get the create category button
        Button btnCreateCategory=(Button) getActivity().findViewById(R.id.btnCreateCategory);
        btnCreateCategory.setOnClickListener(new OnClickListener() {

            //On clicking the Create category button display the fragment containing the Category create form : FormCreateCategoryFragment  
            public void onClick(View v) {

                showCreateCategoryForm();

            }

        });
    }
    public void handleResponse(JSONObject response)
    {

        try {
            System.out.println("Back inside the caller THE CATEGORYLISTFRAGMENT: no of contents in the json--"+response.length());
            noOfCategories=response.length();
            String responseArray[]=new String[noOfCategories];
            for(int i=0;i<noOfCategories;i++)
            {
                responseArray[i]=response.getString("item"+i+"");
                System.out.println(i+":"+responseArray[i]+"\n");
            }

            /*           
             *Display the category names in the grid
             * */
            GridView categoryList=(GridView)getActivity().findViewById(R.id.gridview);          
            ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,responseArray);         
            categoryList.setAdapter(adapter);
            categoryList.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) {


                        showTopics(position);

                }


            });


            /*
             * Check if in dual pane mode
             * */
            View listTopics=getActivity().findViewById(R.id.topics);
            mDualPane=(listTopics!=null && listTopics.getVisibility()==View.VISIBLE);
            Toast.makeText(getActivity(), "mdualpane:"+mDualPane, Toast.LENGTH_LONG).show();

            if (mDualPane) {
                // In dual-pane mode, the list view highlights the selected
                // item.

                Fragment fr=(Fragment)getFragmentManager().findFragmentById(R.id.topics);
                if(fr instanceof FormCreateCategoryFragment)
                {
                    System.out.println("Create Category Form was displayed");

                    showCreateCategoryForm();
                }
                else if(fr instanceof TopicListFragment)
                {
                    showTopics(mCurCheckPosition);
                }   


            } else {

            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

    private void showTopics(int index) {
        // TODO Auto-generated method stub
        mCurCheckPosition = index;

        if(mDualPane)
        {
            TopicListFragment topicListFragment=(TopicListFragment)getFragmentManager().findFragmentById(R.id.topics);
            if(topicListFragment==null || topicListFragment.getShownIndex()!=index)
            {

                FragmentManager fm=getFragmentManager();
                topicListFragment=TopicListFragment.newInstance(index);
                android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.topics, topicListFragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
            else
            {

            }

        }
        else
        {
            System.out.println("The index is:"+index+"\nThe mCurCheckPos:"+mCurCheckPosition+"\n");
            Intent intent=new Intent(getActivity(),TopicsByCategoryActivity.class);
            intent.putExtra("index", mCurCheckPosition);
            startActivity(intent);
        }
    }



    private void showCreateCategoryForm() {
        // TODO Auto-generated method stub

        if(mDualPane)
        {
            FormCreateCategoryFragment formCreateCategory=new FormCreateCategoryFragment();
            android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.topics, formCreateCategory);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();
        }
        else
        {
            System.out.println("In single pane mode : going to display create category form");
            Intent intent=new Intent(getActivity(),FormCreateCategoryActivity.class);
            intent.putExtra("index", mCurCheckPosition);
            startActivity(intent);
        }
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

    }



}

============================================

我正在尝试不同的方法来解决这个问题,但却无法解决这个问题。使用片段管理器有什么问题吗?

===========================================

FormCreateCategoryFragment:

    public class FormCreateCategoryFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        return inflater.inflate(R.layout.fragment_form_create_category, container, false);
    }
    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        System.out.println("\nInside onStart of the FormCreateCategoryFragment===============\n");


    }

}

=============================================== ================

activity_home xml:

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

    <fragment
        android:id="@+id/cat_list_home"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.gitanjal.together.view.CategoryListFragment" />

    <FrameLayout
        android:id="@+id/topics"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        />

</LinearLayout>

3 个答案:

答案 0 :(得分:0)

将xml中的片段声明为

 <FrameLayout
                android:id="@+id/topics_fragment"
                android:layout_width="wrap_parent"
                android:layout_height="wrap_parent"
                 >
            </FrameLayout>

并执行像这样的片段交易

FragmentTransaction ft = getSupportFragmentManager()
                    .beginTransaction();
            ft.replace(R.id.topics_fragment, new FormCreateCategoryFragment());
            ft.commit();
onCreate中的

通过使用TopicsFragment重新编写

来执行片段事务

单击categoryList项时,您不检查实例的类型

 categoryList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) {

here is the problem

do the same here

     Fragment fr=(Fragment)getFragmentManager().findFragmentById(R.id.topics);
                if(fr instanceof FormCreateCategoryFragment)
                {
                    System.out.println("Create Category Form was displayed");

                    showCreateCategoryForm();
                }
                else if(fr instanceof TopicListFragment)
                {
                    showTopics(position);
                } 


            }


        });

答案 1 :(得分:0)

请使用replace(id,fragmentInstance,tagStr)api,你可以使用findFragmentByTag(tag)方法按标签查找片段

答案 2 :(得分:0)

我已经解决了我的问题----

private void showTopics(int index) {
        // TODO Auto-generated method stub
        mCurCheckPosition = index;

        if(mDualPane)
        {
            //---------------------------------------------

            Fragment fr= (Fragment)getFragmentManager().findFragmentById(R.id.topics);
            if(fr instanceof TopicListFragment)
            {

                TopicListFragment topicListFragment=(TopicListFragment)getFragmentManager().findFragmentById(R.id.topics);
                if(topicListFragment==null || topicListFragment.getShownIndex()!=index)
                {

                    FragmentManager fm=getFragmentManager();
                    topicListFragment=TopicListFragment.newInstance(index);
                    android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                    ft.replace(R.id.topics, topicListFragment);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
                }
                else
                {

                }

            }
            else
            {

                android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.topics, TopicListFragment.newInstance(index));
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
}