当前位置: 代码迷 >> Android >> fragment动态添加button,该如何解决
  详细解决方案

fragment动态添加button,该如何解决

热度:90   发布时间:2016-04-27 22:36:26.0
fragment动态添加button
请问各位大侠,如何在一个fragment里面动态添加button等控件并显示出来,能给一些资料链接也行,小弟不甚感激。
------解决思路----------------------
你可以先在布局文件里写好,然后根据需要调用setVisibility(View.GONE)和setVisibility(View.VISIBLE)
------解决思路----------------------
楼上是一种方法,其它方法还是new一个layout放进去
------解决思路----------------------
只有自定义。网上搜吧。我又一个动态添加textview的demo。
------解决思路----------------------
引用:
Quote: 引用:

楼上是一种方法,其它方法还是new一个layout放进去


感谢你的回答!
我的主要问题在这里,就是如何显示这个layout?找到一些在Activity里new layout的资料,没找到在fragment做这个的例子,不知道怎么显示出来。
我曾有个想法,fragment配有一个写好的xml布局文件,这个可以是显示出来的,不知道能不能在代码里用某种方法可以操作这个文件,这时候再来添加按钮,请问这个想法可不可行,谢谢!

在Activity里怎么能,在Fragment中就怎么能,无非就是把 findViewById换成getView().findViewById,或者把this之类的换成getActivity
------解决思路----------------------
View.add(new Button(Activity))
------解决思路----------------------


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
                LinearLayout linearLayout;//假设是LinearLayout
                View view = inflater.inflat(R.layout.你的布局文件名);
                linearLayout = (LinearLayout) view.findViewById(这个布局文件中作为button容器的id);
                Button btn = new Button(getApplicationContext());
                //LayoutParams类是用于child view(子视图) 向 parent view(父视图)传达自己各种属性的容器
                ViewGroup.LayoutParams params =
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                btn.setLayoutParams(params);
                btn.setText("名字");
                linearLayout.addView(btn);
}
  相关解决方案