2016-01-26 35 views
1

目前我正在嘗試創建自己的視圖。現在我找到了有用的教程developer.android.net。我跟着介紹,但我有一些麻煩使用視圖。Android編程創建自己的視圖

首先,我的文件夾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

你是什麼意思的命名空間?那個是從哪裏來的? – PearsonArtPhoto

+1

你的意思是你想知道如何在xml級別包含你的視圖? – thetonrifles

+1

@PearsonArtPhoto按下鏈接,然後點:**定義自定義屬性**。 - > _而不屬於http://schemas.android.com/apk/res/android命名空間,它們屬於http://schemas.android.com/apk/res/ [你的包名] _。 – MyNewName

回答

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_namespaceapp或任何你想有。

在另一方面,如果你想使用你的自定義視圖的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(); 
    } 
} 
+2

)讓我知道它是否有效,或者您是否有其他問題,如果沒有,您可以接受答案,以便其他人可以將其作爲參考 – Mike

+0

yeha,您的解決方案運行良好,我接受了。謝謝! – MyNewName

1

要在XML中使用自定義視圖,您必須使用完全指定的名稱。這是包與類名的結合。所以你的將是company.firstactivity.customViews.cView

1

你可以移動cViewAttributes.xml內容在res到文件attire.xml /值

然後在你的佈局XML你可以聲明的xmlns

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

,然後你可以使用

app:showText="false" 
+0

感謝您的回答! – MyNewName