简体   繁体   English

从另一个 xml 文件定义

[英]Defining from another xml file

I am creating an application that uses a navigation drawer.我正在创建一个使用导航抽屉的应用程序。 However, the navigation drawer layout or design that I am using is from a different XML file, not on my MainActivity.但是,我使用的导航抽屉布局或设计来自不同的 XML 文件,而不是我的 MainActivity。 I have an image in the layout that I am using that I want to apply as SetOnClickListener on my MainActivity.我在我使用的布局中有一个图像,我想在我的 MainActivity 上应用它作为 SetOnClickListener。 But I have no idea how I can define the image that is in a separate XML file in my MainActivity.但我不知道如何定义 MainActivity 中单独 XML 文件中的图像。

in your case you have 2 different XML file(layout files)在您的情况下,您有 2 个不同的 XML 文件(布局文件)

  1. main Activity主要活动

  2. navigation drawer导航抽屉

each layout file must have an own java class to get access to view objects.每个布局文件都必须有自己的 java 类才能访问视图对象。

but if you don't have another java class for navigation drawer, use an LayoutInflater to inflate the XML layout to an view, then you can access an set the Listener to any of views you want但是,如果您没有用于导航抽屉的另一个 java 类,请使用 LayoutInflater 将 XML 布局膨胀为视图,然后您可以访问将 Listener 设置为您想要的任何视图

in main activity add:在主要活动中添加:

LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);

View rootView = li.inflate(R.layout.my_navigation_drawer_layout,null,false);

note* replace your layout file name with my_navigation_drawer_layout注意* 用 my_navigation_drawer_layout 替换你的布局文件名

now you can declare an image view and use findViewById from rootView we create earlier现在您可以声明一个图像视图并使用我们之前创建的 rootView 中的 findViewById

final ImageView img = (ImageView) rootView.findViewById(R.id.myImageViewName)

now you can set listener to img :现在您可以将侦听器设置为 img :

img.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // write your code here!!!
        }
    });

What you want to do, is easy using <include> tag over the XML of the MainActivity class你想要做的,很容易在 MainActivity 类的 XML 上使用<include>标签

<include 
 android:layout = "YOUR LAYOUT OF THE NAVIGATION"/>

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

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