1
我無法理解如何在代碼中實例化自定義佈局。具體而言,我不知道如何定義所需的AttributeSet
參數。如何爲擴展布局定義AttributeSet參數
我已經通過官方文檔走了,但不能換我的頭周圍:
new MyCustomLayout(getActivity(), attrs)
但如何:
http://developer.android.com/training/custom-views/create-view.html http://developer.android.com/reference/android/util/AttributeSet.html
在我的活動,我用它實例我是否定義attrs
?
MyCustomLayout.java
public class MyCustomLayout extends LinearLayout implements
OnClickListener {
...
...
public MyCustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.mycustomxmllayout, this, true);
...
}
...
}
mycustomxmllayout.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="@+id/txt_1"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:lines="1"/>
<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="0dp"
android:minWidth="0dp"
android:background="@null"
android:text="x"
android:layout_weight="1"
/>
</merge>
這很有趣。我希望簡單地重用框架的LinearLayout的現有屬性。這就是爲什麼我擴展它。我不想定義任何自定義屬性。你認爲這是可能的嗎? – faizal 2014-11-01 07:03:35
例如,您想使用什麼attrs?你想在哪裏使用它? – rom4ek 2014-11-01 07:06:58
我只需要'AttributeSet'參數來實例化我的活動中的佈局,即'new MyCustomLayout(getActivity(),attrs)'中的第二個參數。所以,無論是最低要求,讓它工作是我所期待的。我猜這意味着'layout_height'和'layout_width'。如果我可以一起跳過這個參數,那會更好。 – faizal 2014-11-01 07:10:01