[英]Custom linear layout
我正在嘗試創建自己的LinearLayout以使其可重用和模塊化。 首先我的代碼看起來像這樣,工作得很好:
mLlHeader = (LinearLayout)view.findViewById(R.id.ll_header);
mTvCrump = new TextView(mContext);
mTvCrump.setText("> "+((Item) mNavigationHistory.get(mNavigationHistory.size()-1)).getName());
mTvCrump.setId(mNavigationHistory.size()-1);
mTvCrump.setClickable(true);
mTvCrump.setOnClickListener(mBreadcrumpListener);
mBreadcrump.add(mTvCrump);
mLlHeader.addView(mTvCrump,mNavigationHistory.size()-1);
現在我想創建我自己的LinearLayout類,如下所示:
public class Breadcrump extends LinearLayout {
private List<? super Item> mNavigationHistory = new ArrayList<Item>();
private List<TextView> mElements = new ArrayList<TextView>();
public Breadcrump(Context context) {
super(context);
}
public Breadcrump(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void addElement (String name) {
}
}
我的xml看起來像這樣:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/cell_selected"
android:gravity="left"
android:orientation="vertical"
android:padding="5dp" >
<com.client.views.Breadcrump
android:id="@+id/ll_breadcrump"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</LinearLayout>
並像這樣使用它:
mLlHeader = (Breadcrump)view.findViewById(R.id.ll_breadcrump);
....
編輯
我現在在布局xml文件中添加了命名空間,在該文件中我使用自定義視圖和視圖類中具有屬性集的新構造函數。 現在應用程序啟動了。 但它只顯示我的自定義視圖,其余布局是白色的?
在你的布局XML文件中,你可能有這樣的東西:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_header"
... />
嘗試將其更改為
<?xml version="1.0" encoding="utf-8"?>
<com.client.views.Breadcrump
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_header"
... />
編輯:如何在您的活動中使用它?
如果您的XML布局文件名為main.xml ,則只需在活動的onCreate()
方法中調用setContentView(R.layout.main)
。 您的Breadcrump
在內部初始化。 然后你可以使用(Breadcrump)view.findViewById(R.id.ll_header)
來獲取它的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.