【问题标题】:unable to load fragment from activity无法从活动加载片段
【发布时间】:2013-12-27 09:45:39
【问题描述】:

我正在使用 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);  

        }
    });

片段2中的代码

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;

谁能帮帮我

框架布局 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>

点击方法:

  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);

}

}

【问题讨论】:

  • 您是否尝试过扩展 SherlockFragment 和 SherlockFragmentActivity 而不是 Fragment 和 FragmentActivity?
  • 不,我没有延长
  • 所以试试吧,但我不确定这会有所帮助:)
  • @user3069112 发布堆栈跟踪
  • @user3069112 片段不是活动。你需要一个容器,并且需要将片段添加到容器中

标签: android android-fragments


【解决方案1】:

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

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

Activity 缺少 setContentView

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>

【讨论】:

  • 每次我想去下一个片段时我应该写框架布局
  • @user3069112 有一个例子@developer.android.com/reference/android/app/Fragment.html。即使在 sdk 示例中,您也会找到相关示例。
  • 好的,谢谢,我应该在框架布局中编写所有视图,还是在我在框架布局中编写所有视图时不需要它所有元素都会受到任何建议的干扰
  • @user3069112 你弄糊涂了。 FrameLayout 旨在托管片段。所以你的做法是错误的。在activity_main.xml。有你想要的框架布局。有你不希望作为框架布局子级的图像按钮。指定宽度和高度。现在在 java 代码中将片段添加到容器中,即 framelayout。对于 framgent 布局,您有一个不同的布局 xml,它在片段的 onCreateView 中膨胀
  • 我和你说的一样,但它给出了错误我已经在不同的 xml 文件中声明了框架布局并添加了容器的 id,但它给了我错误
【解决方案2】:

你不能这样调用 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);

【讨论】:

  • new Fragment2(contextHere)。我相信片段必须有一个无参数构造函数
  • 但是当 Fragment 创建时,该特定类的上下文将作为 arg 传递到那里。而且我用过很多次,效果很好。
  • 检查这个developer.android.com/reference/android/support/v4/app/…。引用“默认构造函数。每个fragment必须有一个空的constructor,所以在恢复activity的状态时可以实例化。强烈建议子类不要有其他带参数的构造函数,因为fragment重新调用时不会调用这些构造函数- 实例化;相反,参数可以由调用者使用 setArguments(Bundle) 提供,然后由 Fragment 使用 getArguments() 检索。"
  • 片段片段 = new Fragment2(); FragmentManager fm =getSupportFragmentManager(); FragmentTransaction 交易 = fm.beginTransaction(); transaction.replace(R.id.content_frame, 片段); transaction.commit();
  • java.lang.IllegalArgumentException: 未找到片段 Fragment2{b3cf5c80 #0 id=0x7f04008f} 的 id 0x7f04008f (com.arivoli.amec:id/content_frame) 的视图
【解决方案3】:

在activity中,可以使用fragment加载;

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;
    }
}

和一个简单的 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="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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多