简体   繁体   English

Android Studio 1.4-解释activity_main.xml和content_main.xml

[英]Android Studio 1.4 - Explain activity_main.xml and content_main.xml

I just updated my Android Studio to 1.4, and I'm a bit confused about activity_main.xml and the other xml file content_main.xml. 我刚刚将Android Studio更新至1.4,但对activity_main.xml和其他xml文件content_main.xml感到有些困惑

I have this app that programatically generates xml. 我有这个以编程方式生成xml的应用程序。 Everything is fine, except I don't have the action bar. 一切都很好,除非我没有操作栏。

My onCreate is like this: 我的onCreate是这样的:

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


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    ...
   // set layout programatically


  setContentView(myCustomXML);

How do I get the action bar? 如何获得操作栏? There must be some very simple solution to this. 对此必须有一些非常简单的解决方案。

Many design components that were introduced with Android Lollipop version. Android Lollipop版本引入了许多设计组件 The main problem you are probably not awared right now is the Toolbar Widget . 您现在可能尚未意识到的主要问题是Toolbar Widget

As you can see in your AndroidManifest.xml , for MainActivity there is "...NoActionBar" theme used. 正如您在AndroidManifest.xml看到的那样,对于MainActivity ,使用了“ ... NoActionBar”主题。 Therefor there is no default actionbar placed on top od activity_main layout. 因此,没有默认的动作栏放置在activity_main布局的顶部。 Instead of that there is android.support.v7.widget.Toolbar component used and it is part of content XML. 取而代之的是使用了android.support.v7.widget.Toolbar组件,它是内容XML的一部分。

Notice, that Toolbar is part of activity_main.xml and probably not part of your MyCustomXML . 请注意,该Toolbaractivity_main.xml一部分,可能不是MyCustomXML一部分。

If this is not your problem, then you probably just need to setSupportActionBar(android.support.v7.widget.Toolbar) or setActionBar(android.widget.Toolbar) . 如果这不是您的问题,则可能只需要设置setSupportActionBar(android.support.v7.widget.Toolbar)setActionBar(android.widget.Toolbar)

After you have set action bar from your layout.xml you can get it via getSupportActionBar() / getActionBar() methods. layout.xml 设置操作栏后 ,可以通过getSupportActionBar() / getActionBar()方法获取它。

Hopefuly, this is what you are looking for, because your question is not 100% clear 希望如此,这就是您要寻找的,因为您的问题不是100%清楚

Edit: Do not use setContentView() twice and do not expect anything to work if you work with views before setContentView() method is called (Toolbar is also view) 编辑:不要两次使用setContentView() ,并且如果在调用setContentView()方法之前使用视图,则不要指望任何东西能工作(工具栏也是视图)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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