无法从活动中加载片段

时间:2013-12-27 09:45:40

标签: android android-fragments

我正在使用Sherlock Fragments库来滑动菜单。我的问题是当我点击活动中的按钮时我无法加载片段。我得到java.lang.classcastException 到android.app.activity。

我已导入:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

但我仍然收到错误。

mainActivity的代码。

public class AmecmainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

      actionnetwork=(ImageButton)findViewById(R.id.ActionNetwork);
      actionnetwork.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        Intent action=new Intent(v.getContext().getApplicationContext(),
                Fragment2.class);
        startActivity(action);  

        }
    });

和fragment2中的代码

public class Fragment2 extends Fragment{

    Fragment fragment;
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.actionnetworklogin, container, false);
    Button login = (Button)view.findViewById(R.id.login);
    login.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              });
    } 
return view;

任何人都可以帮助我

framelayout 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:orientation="vertical" >

          <FrameLayout
           android:id="@+id/fragment_container"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:background="?android:attr/detailsElementBackground" />

    </LinearLayout>

onclick方法:

  actionnetwork=(ImageButton)findViewById(R.id.ActionNetwork);
  actionnetwork.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
          Fragment fragment = new Fragment2();
          FragmentManager fm =getSupportFragmentManager();
          FragmentTransaction transaction = fm.beginTransaction();
          transaction.replace(R.id.fragment_container, fragment); 
          transaction.commit(); 
    }
});



  fragment2 xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Second Fragment"
    android:textSize="15pt" />

    </RelativeLayout>



mainactivity:

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="match_parent"
    android:orientation="vertical" >


   <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:scaleType="fitXY" >

         <ImageButton
            android:id="@+id/ActionNetwork"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="28dp"
            android:layout_marginLeft="25dp"
            android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>

以前片段的代码

      public boolean onOptionsItemSelected(MenuItem item) 
    {
    switch (item.getItemId()) 
    {
    case R.id.menuIcon:
         toggle();
         break; 
     case android.R.id.home:

         getFragmentManager().popBackStackImmediate();
                            }
    return super.onOptionsItemSelected(item);
}

fragment2.class文件

公共类Fragment1扩展了Fragment {

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment1, container, false);
    Button clicked=(Button)view.findViewById(R.id.clickedmove);
    clicked.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
              Fragment fragment = new Fragment2();
              FragmentManager fm =getFragmentManager();
              FragmentTransaction transaction = fm.beginTransaction();
              transaction.addToBackStack(null);
              transaction.replace(R.id.contentFragment, fragment); 
              transaction.commit(); 
        }
    });
    return view;
}

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

}

}

3 个答案:

答案 0 :(得分:3)

Fragment2是一个片段,而不是一个Activity。片段由活动托管。以下是错误的

 Intent action=new Intent(v.getContext().getApplicationContext(),Fragment2.class);
 startActivity(action);

setContentView

,你遗漏了Activity。{/ p>
public class AmecmainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // missing

然后

您需要在activity_main.xml

中使用Container
<FrameLayout 
      android:id="@+id/fragment_container" 
      android:layout_width="match_parent" 
      android:layout_height="200dp"
      android:background="?android:attr/detailsElementBackground" />

然后在onClick

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment2 fragment = new Fragment2();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

编辑:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/imageButton1"
        android:id="@+id/fragment_container"
       >
    </FrameLayout>

</RelativeLayout>

答案 1 :(得分:1)

你不能像这样调用Fragment:

你必须使用它:

 void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.simple_fragment, fragment);
    ft.setTransition(transition);
    if (addBacktoStack)
        ft.addToBackStack(null);
    ft.commit();

}

并像这样调用这个方法:

 addfragment(new Fragment2(contextHere),true,FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

答案 2 :(得分:1)

在活动中,可以使用;

加载片段
FragmentManager fragmentManager = getSupportFragmentManager();        
fragmentManager.beginTransaction()
               .replace(R.id.container_main, new MyFragment())
               .commit();

其中 MyFragment 为;

public class MyFragment extends android.support.v4.app.Fragment {


    public MyFragment() {
        // Required empty public constructor
    }
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_whats_trending, container, false);
        return rootView;
    }
}

和一个简单的片段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:paddingBottom="@dimen/activity_vertical_margin"
 tools:context="in.stocksphere.stocksphere.MyFragment$PlaceholderFragment" >

            <TextView android:text="@string/ta_user"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content" />

</RelativeLayout>