简体   繁体   English

Android:将自己的视图添加到LinearLayour

[英]Android: Add own View to LinearLayour

I have created an own View: 我创建了一个自己的视图:

    private class SampleView extends View {

and I want to "plant" this View into a LinearLayout which I created in an xml file. 我想将此视图“植入”我在xml文件中创建的LinearLayout中。 How do I do that? 我怎么做? Can someone help me? 有人能帮我吗?

add in your layout file 在您的布局文件中添加

<LinearLayout >

<com.yourpackagename.SampleView />

<LinearLayout> 

or 要么

LinearLayout lLayout = (LinearLayout)findViewById(R.id.linearlayout);
lLayout.addView(new SampleView());

Just use the fully qualified name of your custom view class 只需使用自定义视图类的完全限定名称

<LinearLayout ...>
  <your.package.SampleView 
    android:layout_width=".."
    android:layout_height=".."
    ..
  >
  </your.package.SampleView >
  ..
</LinearLayout>

However, remove "private" from your class definition, and if it a nested class add static . 但是,从类定义中删除“ private”,如果是嵌套类,则添加static

You can't use inner classes at this point 您目前无法使用内部类

Try to add your custom View like this: 尝试添加您的自定义View如下所示:

<view
   class="test.project.app.Compass$SampleView"
   //... other attributes
/>

Your custom View class must be public and static for the above code to work. 您的自定义View类必须是public并且是static的,以上代码才能正常工作。 Another option is to put the SampleView in its own file and simply use the code from the answers above. 另一个选择是将SampleView放在其自己的文件中,并仅使用上面答案中的代码。

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

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