安卓动态增加按钮
首先了解一下LayouInflater类: 将一个layout xml文件实例化为相应的View 对象。他永远不会直接使用,而是使用 getLayoutInflater() 或者 getSystemService(String) 来获得标准的LayoutInflater实例,这个实例已经将context连接起来,为正在运行的设备配置正确。 比如: [java] view plaincopy LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); public View inflate (int resource, ViewGroup root) Since: API Level 1 Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. Parameters resource ID for an XML layout resource to load (e.g., R.layout.main_page) root Optional view to be the parent of the generated hierarchy. Returns The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file. 假如有一个这样的xml文件(guess_button.xml) 放入到一个buttonTableLayout: [html] view plaincopy <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/newGuessButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> (guess_button.xml) [html] view plaincopy <TableLayout android:id="@+id/buttonTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:stretchColumns="0,1,2" > <TableRow android:id="@+id/tableRow0" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> </TableLayout> (main.xml中定义的需要被扩充的buttonTableLayout,假设其在程序中的引用也叫buttonTableLayout, 即buttonTableLayout =(TableLayout) findViewById(R.id.buttonLayout);) 现在我们将其第一行进行扩充: [java] view plaincopy LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); Button newGuessButton =(Button)inflater.inflater(R.layout.guess_button,null); //获得按钮 newGuessButton.setText("abc"); //设置按钮文本 newGuessButton.setOnClickListener(guessButtonListener); //设置Listener (TableRow) buttonTableLayout.getChildAt(1); //将newGuessButton加到table第一行 OK 整个流程就完成了
标签:
phone 开发
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架