Android编程创建自己的视图

时间:2016-01-26 19:42:08

标签: android

目前我正在尝试创建自己的视图。现在我在developer.android.net找到了有用的教程。我遵循了介绍,但是使用视图时遇到了一些麻烦。

首先,我的文件夹structur

enter image description here

cView.java

package company.firstactivity.customViews;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

public class cView extends View{
    public cView(Context context, AttributeSet attrs){
        super(context,attrs);
    }
}

cViewAttributes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="cView">
        <attr name="showText" format="boolean" />
    </declare-styleable>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="company.firstactivity.MainActivity">

</RelativeLayout>

我的问题是使用视图的命名空间。什么是命名空间?任何人都可以帮助我吗?

提前致谢!

3 个答案:

答案 0 :(得分:4)

xml中的命名空间可以是任何内容,但它应始终具有值http://schemas.android.com/apk/res-auto。请参阅以下示例中的my_custom_namespace以了解您的使用方式:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:my_custom_namespace="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="company.firstactivity.MainActivity">

    <company.firstactivity.customViews.cView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        my_custom_namespace:showText="true"/>
</RelativeLayout>

您可以将my_custom_namespace更改为app或您想要的任何内容。

另一方面,如果您想在自定义视图的java代码中使用自定义属性,可以这样读取此值:

public cView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initView(context, attrs);
}

public cView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initView(context, attrs);
}

private void initView(Context context, AttributeSet attrs) {
    if (attrs != null) {
        TypedArray styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.cView);
        boolean shouldShowText = styledAttrs.getBoolean(R.styleable.cView_showText, false);
        styledAttrs.recycle();
    }
}

答案 1 :(得分:1)

要在XML中使用自定义视图,必须使用完全指定的名称。这是包与类名的组合。所以你的company.firstactivity.customViews.cView

答案 2 :(得分:1)

您可以将cViewAttributes.xml的内容移动到res / values

中的文件attire.xml

然后在你的布局xml中你可以声明xmlns

Meteor.methods({
    'someRequest': function(params){
        var wrap = Meteor.wrapAsync(anAsyncFunction);
        return wrap(params);
    },
});

然后你可以使用

xmlns:app="http://schemas.android.com/apk/res-auto"