简体   繁体   中英

How to inflate layout from extended activity?

I have extended BaseActivity from ActionBarActivity , in which I set the activity's content. There's a FrameLayout in the layout file I use.

When I extend BaseActivity to use in eg MainActivity , I'd like MainActivity to inflate the FrameLayout with a custom layout file.

I couldn't come up with a solution. I always got errors. This is how far I came.

BaseActivity.java

public class BaseActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base);
    }
}

MainActivity.java

public class MainActivity extends BaseActivity {

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

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        FrameLayout mFrame = (FrameLayout) findViewById(R.id.content);
        mFrame.addView(LayoutInflater.from(context).inflate(R.layout.activity_nav_test, mFrame, true));
        return super.onCreateView(parent, name, context, attrs);
    }

Thanks a lot for your help! Chris

Your approach seems to be proper but add view inside frame layout in onCreate method instead.

public class MainActivity extends BaseActivity {

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


FrameLayout mFrame = (FrameLayout) findViewById(R.id.content);
        mFrame.addView(LayoutInflater.from(this).inflate(R.layout.activity_nav_test, mFrame, true));
}

In this method :

 @Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    FrameLayout mFrame = (FrameLayout) findViewById(R.id.content);
    mFrame.addView(LayoutInflater.from(context).inflate(R.layout.activity_nav_test, mFrame, true));
    return super.onCreateView(parent, name, context, attrs);
}

You must return ur custom view. Try this. I hope it helps

return mFrame;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM