zoukankan      html  css  js  c++  java
  • addview

    android界面中,添加一个子视图,有两种方法:一、在xml布局文件中写死;二、在程序中动态添加。

    这里,介绍一下如何在程序中动态添加一个子视图。

    例子:

    1 <LinearLayout  
    2    android:id="@+id/viewObj"  
    3    android:layout_width="wrap_content"  
    4    android:layout_height="wrap_content"  
    5    android:orientation="vertical"  
    6    android:layout_x="1px"  
    7    android:layout_y="1px"  
    8 />  
     1 public class helloWorld extends Activity {  
     2    
     3    public void onCreate(Bundle savedInstanceState) {  
     4       super.onCreate(savedInstanceState);  
     5       setContentView( R.layout.main );  
     6    
     7       // 取得LinearLayout 物件   
     8       LinearLayout ll = (LinearLayout)findViewById(R.id.viewObj);  
     9    
    10       // 将TextView 加入到LinearLayout 中   
    11       TextView tv = new TextView(this);  
    12       tv.setText("Hello World");  
    13       ll. addView ( tv );  
    14    
    15       // 将Button 1 加入到LinearLayout 中   
    16       Button b1 = new Button(this);  
    17       b1.setText("取消");  
    18       ll. addView ( b1 );  
    19    
    20       // 将Button 2 加入到LinearLayout 中   
    21       Button b2 = new Button(this);  
    22       b2.setText("确定");  
    23       ll. addView ( b2 );  
    24    
    25       // 从LinearLayout 中移除Button 1   
    26       ll. removeView ( b1 );  
    27    }  
    28 }  

    效果:

    流程:1、在要加入子视图的xml文件里,定义一个framelayout或LinearLayout,说明要加入视图的位置、大小等。

             2、在程序中,new出这个视图,找到framelayout或LinearLayout,直接用framelayout.addView(我们自己new的视图)。

              例:mainView = new LinearLayout(mCtx);
                    mainView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

                 可用setLayoutParams来设置我们new的这个视图的宽、高。

    那么,怎么控制添加的视图的位置了?

    例:创建一个TextView视图

       TextView tv = new TextView(mCtx);
       tv.setLayoutParams(new LayoutParams(100, 40));
       tv.setText("网络连接中...");

        添加到指定位置:

        ViewGroup vg = (ViewGroup)v.getParent();
       FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
       params.gravity = Gravity.CENTER;//添加到这个vg视图的正中间

      //上面两句话等同于FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,Gravity.CENTER);
       vg.addView(tv,params);

    效果:

  • 相关阅读:
    AppDomain以及如何改变web.config / App.config位置
    事实与谎言 软件工程
    REST WebServices学习
    项目沟通案例:最近项目开发中的扯皮问题
    用户界面设计的技巧与技术(By Scott W.Ambler)
    C#集合类(HashTable, Dictionary, ArrayList)与HashTable线程安全
    About
    Leading by Example
    Pair Programming vs. Code Reviews
    使用jqueryeasyui写的CRUD插件(2)
  • 原文地址:https://www.cnblogs.com/wyqfighting/p/3088827.html
Copyright © 2011-2022 走看看