安卓设置AttributeSet

XmlPullParser parser = getResources().getXml(R.layout.textview);
    AttributeSet attributes = Xml.asAttributeSet(parser);

    int type;

    while ((type = parser.next()) != XmlPullParser.START_TAG &&
            type != XmlPullParser.END_DOCUMENT) {
                    // Empty
    }   

  TextView tv=new TextView(this,attributes);




有时候我们需要在代码中动态创建view,并把它加入到当前的viewGroup中,动态创建view一般使用LayoutInflater或者构造函数,在这里使用构造函数,有三个构造函数可用,比如动态创建TextView,可以使用这三个构造函数:

    TextView(Context context)
    TextView(Context context, AttributeSet attrs)
    TextView(Context context, AttributeSet attrs, int defStyleAttr)

    其中context是当前Activity的Context,attrs是一组属性值,例如layout_width,layout_height等等,defStyleAttr和控件的style有关,本篇暂不考虑.

    context很容易拿到,那么attrs是怎么拿到的呢,查看文档发现官网上有给出:

    XmlPullParser parser = resources.getXml(myResouce);
    AttributeSet attributes = Xml.asAttributeSet(parser);

    resources可以用context.getResources()获取,这是本地资源信息的类,myResouce是资源ID.

    我们在res/layout下创建资源XML文件textview.xml:

    <TextView
    xmlns:Android="http://schemas.android.com/apk/res/android"
    android:background="#ff00ff00"
    android:text="hello world!"/>

    拿到这两个参数,现在就可以调用第二个构建函数创建view了吗?嗯,我也是这样想的,那么问题来了,创建view之后发现没有任何显示,这是为什么呢,试着给它写入文本,在创建后调用tv.setText("hello");这回有显示了,背景也不是我们写在XML中的值,这说明attrs没有发挥作用.推断原因可能是attrs中的值不对,调用parser.getAttributeCount()发现返回的是-1,说明XML没有被正确解析!

    想起使用LayoutInflater也是使用XML文件生成了VIEW,或许可以看看它的代码:

    public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }

    public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        if (DEBUG) System.out.println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().getLayout(resource);//这里和getXml效果一样
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

    public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final AttributeSet attrs = Xml.asAttributeSet(parser); //这里也和我们之前做的一样
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            View result = root;

            try {
                // Look for the root node. !!这里是我们没有做过的!!
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();
                ....更多的代码隐藏起来了

            } catch (XmlPullParserException e) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (IOException e) {
                InflateException ex = new InflateException(
                        parser.getPositionDescription()
                        + ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }

            return result;
        }
    }

    这里发现我们在创建attrs时,没有去查找XML的根节点:

   while ((type = parser.next()) != XmlPullParser.START_TAG &&
            type != XmlPullParser.END_DOCUMENT) {
                    // Empty
    }

    现在在代码中加上这段,发现XML的设置起使用了,并且parser.getAttributeCount()也返回了2,正是我们属性的个数.

    总结一下流程:

    XmlPullParser parser = getResources().getXml(R.layout.textview);
    AttributeSet attributes = Xml.asAttributeSet(parser);

    int type;

    while ((type = parser.next()) != XmlPullParser.START_TAG &&
            type != XmlPullParser.END_DOCUMENT) {
                    // Empty
    }   

    TextView tv=new TextView(this,attributes);

    努力了这么久,只为了创建一个View,还不如用LayoutInflater呢,有人这样想吗?完全正确,我之所以这样做是因为我要获取到attributes来进行布局设置,很多例子中,生成一个view之后就直接setContentView去了,这在项目中应该很少这么干的,因为我们还有其他的view要显示,创建的view只是显示在大布局中的一块而已.我们要把这个view加入到其它的布局中去,一般调用的是addView:

    void     addView(View child, int index, ViewGroup.LayoutParams params)  Adds a child view with the specified layout parameters.
    void     addView(View child, ViewGroup.LayoutParams params)  Adds a child view with the specified layout parameters.
    void     addView(View child, int index)   Adds a child view.
    void     addView(View child) Adds a child view.
    void     addView(View child, int width, int height) Adds a child view with this ViewGroup's default layout parameters and the specified width and height.

    特别说明,只有继承了ViewGroup的类才有这些函数,比如RelativeLayout,LinearLayout等.child参数是我们刚刚创建的view,index是我们的view在此layout中的Z序,params是布局参数.

    不同的布局类有不同的布局参数类.它们都继承自ViewGroup.LayoutParams,例如 LinearLayout.LayoutParams, RelativeLayout.LayoutParams等等,关注RelativeLayout.LayoutParams的构造函数:

    RelativeLayout.LayoutParams(Context c, AttributeSet attrs)
    RelativeLayout.LayoutParams(int w, int h)  //可以指定长和宽
    RelativeLayout.LayoutParams(ViewGroup.LayoutParams source)
    RelativeLayout.LayoutParams(ViewGroup.MarginLayoutParams source)

    从上面看出,我们在构造时可以设置view的长和宽,使用ViewGroup.MarginLayoutParams可以设置view的边距,其它的只能通过attrs来设置了,这就是我要创建attrs的目的.使用attrs完全可以精细化操作布局,下面来一个简单的示例,动态创建一个textView,并把它加入到主布局文件的RelativeLayout中,并局中显示:

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //MainActivity.java  
  2. package com.example.helloworld;  
  3.   
  4. import java.io.IOException;  
  5.   
  6. import org.xmlpull.v1.XmlPullParser;  
  7. import org.xmlpull.v1.XmlPullParserException;  
  8.   
  9. import android.app.Activity;  
  10. import android.os.Bundle;  
  11. import android.util.AttributeSet;  
  12. import android.util.Log;  
  13. import android.util.Xml;  
  14. import android.view.Menu;  
  15. import android.view.MenuItem;  
  16. import android.view.View;  
  17. import android.view.View.OnClickListener;  
  18. import android.widget.Button;  
  19. import android.widget.RelativeLayout;  
  20. import android.widget.RelativeLayout.LayoutParams;  
  21. import android.widget.TextView;  
  22.   
  23.   
  24. public class MainActivity extends Activity {  
  25.   
  26.     private RelativeLayout mRelativeLayout;  
  27.     @Override  
  28.     protected void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.activity_main);  
  31.         mRelativeLayout=(RelativeLayout)findViewById(R.id.relativelayout1);  
  32.         ((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {  
  33.               
  34.             @Override  
  35.             public void onClick(View v) {  
  36.                 // TODO Auto-generated method stub  
  37.                 XmlPullParser parser = MainActivity.this.getResources().getXml(R.layout.textview);  
  38.                 AttributeSet attributes = Xml.asAttributeSet(parser);  
  39.                 int type;  
  40.                 try{  
  41.                     while ((type = parser.next()) != XmlPullParser.START_TAG &&  
  42.                             type != XmlPullParser.END_DOCUMENT) {  
  43.                         // Empty  
  44.                     }  
  45.       
  46.                     if (type != XmlPullParser.START_TAG) {  
  47.                         Log.e("","the xml file is error!\n");  
  48.                     }     
  49.                 } catch (XmlPullParserException e) {  
  50.                     // TODO Auto-generated catch block  
  51.                     e.printStackTrace();  
  52.                 } catch (IOException e) {  
  53.                     // TODO Auto-generated catch block  
  54.                     e.printStackTrace();  
  55.                 }  
  56.                 Log.d("",""+parser.getAttributeCount());  
  57.                 TextView tv=new TextView(MainActivity.this,attributes);  
  58.                 RelativeLayout.LayoutParams params=new LayoutParams(MainActivity.this,attributes);  
  59.                 mRelativeLayout.addView(tv,0,params);  
  60.             }  
  61.         });  
  62.     }  
  63.   
  64.     @Override  
  65.     public boolean onCreateOptionsMenu(Menu menu) {  
  66.         // Inflate the menu; this adds items to the action bar if it is present.  
  67.         getMenuInflater().inflate(R.menu.main, menu);  
  68.         return true;  
  69.     }  
  70.   
  71.     @Override  
  72.     public boolean onOptionsItemSelected(MenuItem item) {  
  73.         // Handle action bar item clicks here. The action bar will  
  74.         // automatically handle clicks on the Home/Up button, so long  
  75.         // as you specify a parent activity in AndroidManifest.xml.  
  76.         int id = item.getItemId();  
  77.         if (id == R.id.action_settings) {  
  78.             return true;  
  79.         }  
  80.         return super.onOptionsItemSelected(item);  
  81.     }  
  82. }  
res/layout/activity_main.xml
[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context="com.example.helloworld.MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textView1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="@string/hello_world" />  
  16.   
  17.     <Button  
  18.         android:id="@+id/button1"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_below="@+id/textView1"  
  22.         android:text="Button" />  
  23.   
  24.     <RelativeLayout  
  25.         android:id="@+id/relativelayout1"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="200dp"  
  28.         android:layout_alignLeft="@+id/button1"  
  29.         android:layout_below="@+id/button1"  
  30.         android:background="#ffff0000"  
  31.         >  
  32.     </RelativeLayout>  
  33.   
  34. </RelativeLayout>  
res/layout/textview.xml
[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TextView  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="wrap_content"   
  5.     android:layout_height="wrap_content"  
  6.     android:layout_centerInParent="true"  
  7.     android:background="#ff00ff00"  
  8.     android:visibility="visible"  
  9.     android:text="hello world!"/>  


示例图片:



原文地址:http://blog.csdn.net/crazyman2010/article/details/41846157

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值