java 动态片段实例化

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 动态片段实例化相关的知识,希望对你有一定的参考价值。

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
 
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();
        } 
    } 
} 

以上是关于java 动态片段实例化的主要内容,如果未能解决你的问题,请参考以下文章

java 片段实例化器

启用 Proguard 后无法实例化片段

如何在java中动态实例化具有不同数量参数的java类?

片段事务中的实例化错误

Android - 试图实例化一个不是片段的类

调用片段活动错误无法实例化活动。无法转换为 android.app.Activity