如何从活动中调用片段

时间:2015-03-30 10:35:12

标签: android

我正在从一个活动中调用一个片段类,所以我无法调用这个片段类,因为我收到的错误如下所示,这是我的完整代码所以任何人都可以帮助我,请提前感谢

Activity class
public class Second extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_second);

    }

    public void onClickNext(View view) {
        Intent intent = new Intent(Second.this, MainActivity.class);
        startActivityForResult(intent, 400);
        overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_bottom);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
    }

    public void btnHome(View view) {
        Intent intent = new Intent(Second.this, Welcome.class);
        startActivity(intent);
    }

    public void aboutUsClick(View view) {
        Fragment fragment = null;
        fragment = new AboutFragment();


        startActivity(new Intent(this, AboutFragment.class));


    }
}

片段类

package com.example.lunetta;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class AboutFragment extends Fragment{


    public AboutFragment(){

    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fragment_layout_about, container,
                false);
        return view;
    }

}

Android Manifest

 <activity
            android:name="com.example.lunetta.AboutFragment"
            android:label="@string/title_fragment_layout_about" >
 </activity>

我在log cat中遇到了这种类型的错误

03-30 10:24:34.876: E/AndroidRuntime(5299): FATAL EXCEPTION: main
03-30 10:24:34.876: E/AndroidRuntime(5299): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lunetta/com.example.lunetta.AboutFragment}: java.lang.ClassCastException: com.example.lunetta.AboutFragment cannot be cast to android.app.Activity
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.os.Looper.loop(Looper.java:137)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at java.lang.reflect.Method.invokeNative(Native Method)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at java.lang.reflect.Method.invoke(Method.java:511)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at dalvik.system.NativeStart.main(Native Method)
03-30 10:24:34.876: E/AndroidRuntime(5299): Caused by: java.lang.ClassCastException: com.example.lunetta.AboutFragment cannot be cast to android.app.Activity
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-30 10:24:34.876: E/AndroidRuntime(5299):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-30 10:24:34.876: E/AndroidRuntime(5299):     ... 11 more

3 个答案:

答案 0 :(得分:1)

原因是,片段不是活动。它是Activity的一部分,它使用与活动几乎相同的生命周期,但至少你必须有一个用片段替换容器的活动。

请记住:片段的使用有几个原因。一个是你可以在你的活动中使用几个片段(布局无论如何)并替换它们。其次,它可以更灵活地构建。

如果你想使用片段,你可以这样做:

public void aboutUsClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
    ft.remove(prev);
}
ft.addToBackStack(null);

// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}

而Fragment类扩展了DialogFragment。

另一个想法是创建一个Class,它加载一个替换你的片段的布局。

为此,您需要创建一个可能如下所示的新布局(来自andorid开发人员样本)

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

<fragment android:name="com.example.android.fragments.HeadlinesFragment"
          android:id="@+id/headlines_fragment"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="match_parent" />

<fragment android:name="com.example.android.fragments.ArticleFragment"
          android:id="@+id/article_fragment"
          android:layout_weight="2"
          android:layout_width="0dp"
          android:layout_height="match_parent" />

然后启动加载/保存片段的Activity。

public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check that the activity is using the layout version with
        // the fragment_container FrameLayout
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            // Create a new Fragment to be placed in the activity layout
            HeadlinesFragment firstFragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            firstFragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, firstFragment).commit();
        }
    }
}

答案 1 :(得分:0)

这是错误的:

  

startActivity(new Intent(this,AboutFragment.class));

您正在开始一项活动,但AboutFragment.class是一个片段,而不是一个活动。您可以使用replace来初始化片段。

答案 2 :(得分:0)

您没有正确使用片段。片段应该是活动的一部分,不能使用startActivity()启动。你应该

  

i)将片段添加到活动的xml布局文件或中   ii)以编程方式将其添加到您的活动中