2015-02-11 66 views
1

這裏我在android中創建了自己的自定義小部件,並且它們都正常工作。但是,我喜歡20個xml文件,我不想將xml中的EditText更改爲com.example.customwidget.MyEditText,我所有的xml佈局都是這樣。任何快速的方式來做到這一點?在android xml中查看的自定義命名空間

例如: 下面的xml不起作用。它會使應用程序崩潰,因爲android sdk小部件中沒有MyEditText,這是我自己的小部件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <MyEditText 
     android:id="@+id/editText1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" 
     android:ems="10" 
     android:inputType="number" > 

     <requestFocus /> 
    </MyEditText> 

</RelativeLayout> 

然而, 這一個將工作:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <com.example.customwidget.MyEditText 
     android:id="@+id/editText1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentRight="true" 
     android:layout_alignParentTop="true" 
     android:ems="10" 
     android:inputType="number" > 

     <requestFocus /> 
    </com.example.customwidget.MyEditText> 

</RelativeLayout> 

我想要做的是簡單地保持EditText標籤中的XML。不過,我想按我自己的習慣EditText

好吧,我知道我將不得不改變類的名稱首先要EditText而不是MyEditText,但我怎樣才能讓所有的XML佈局文件知道,我想我的自定義EditText,而不是原生一個?

回答

2

定製實現LayoutInflater.Factory並將其設置爲your activity's LayoutInflater

這裏有一個這樣的工廠的例子:

public class MyLayoutInflaterFactory implements LayoutInflater.Factory 
{ 
    public View onCreateView(String name, Context context, AttributeSet attrs) 
    { 
     if ("EditText".equals(name)) 
      return new MyEditText(context, attrs); 
     return null; 
    } 
} 

然後,你需要在你的活動來使用它:

public class MyActivity extends Activity 
{ 
    ⋮ 

    LayoutInflater layoutInflater; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     layoutInflater = LayoutInflater 
      .from(this) 
      .cloneInContext(this) 
      .setFactory(new MyLayoutInflaterFactory()); 

     setContentView(layoutInflater.inflate(R.layout.my_activity, null)); 
    } 

    @Override 
    public LayoutInflater getLayoutInflater() 
    { 
     return layoutInflater; 
    } 

    ⋮ 
} 
+0

沒有,這不是我想要什麼,我相信你弄錯了我。我想要的是,當我在xml中使用'EditText'時,它不會使用本地EditText,它將使用我修改過的我的EditText' – 2015-02-11 03:07:33

+0

這是實現它的方法。 – StenSoft 2015-02-11 03:09:25

+0

啊我覺得我現在開始讓你......但我不知道如何去做,任何提示都會被讚賞:) – 2015-02-11 03:11:20