如何在Android中从XML膨胀视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10123159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:34:29  来源:igfitidea点击:

How to Inflate view from XML in Android?

androiduser-interfaceviewandroid-tablelayoutandroid-inflate

提问by Gnanam R

I'm creating a tableLayout [given in XML]

我正在创建一个 tableLayout [以 XML 格式给出]

adding table Row [created in XML and inflating in Java]

添加表行 [用 XML 创建并用 Java 膨胀]

also adding 2 textview to the table Row [created in XML and inflating in JAVA]

还将 2 个 textview 添加到表 Row [在 XML 中创建并在 JAVA 中膨胀]

I'm able to get only the background and textcolors but not the layout properties like width, height and margin to get table view.

我只能获取背景和文本颜色,但不能获取宽度、高度和边距等布局属性来获取表格视图。

回答by ChallengeAccepted

  1. First declare your inflater.

    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
    
  2. Identify and inflate the new view you seek to project on the current view.

    View view = inflater.inflate(R.layout.new_layout,null);
    
  3. You would want to add your new inflated view to your layout.

    main.addView(view);
    
  1. 首先声明你的充气机。

    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
      (Context.LAYOUT_INFLATER_SERVICE);
    
  2. 识别并扩展您要在当前视图上投影的新视图。

    View view = inflater.inflate(R.layout.new_layout,null);
    
  3. 您可能希望将新的膨胀视图添加到您的布局中。

    main.addView(view);
    

You can reference additional information here: http://developer.android.com/reference/android/view/LayoutInflater.html

您可以在此处参考其他信息:http: //developer.android.com/reference/android/view/LayoutInflater.html

Update May 2019 (Kotlin):This is how you would inflate a view from XML in Kotlin. this is referring to an activity.

2019 年 5 月更新(Kotlin):这是在 Kotlin 中从 XML 扩充视图的方式。这是指一项活动。

val view = this.layoutInflater.inflate(R.layout.dialog_upgrade, null)
mainLayout.addView(view)

回答by user987760

LayoutInflater li = LayoutInflater.from(getApplicationContext());
View cv = li.inflate(R.layout.your_layout, null);

mainlayout.addView(cv);

回答by Shankar Agarwal

LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService      (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.your_layout,null);
mainlayout.addView(view;

follow the above to inflate view.

按照上面的方法来膨胀视图。