Search code examples
javaandroidandroid-layoutandroid-custom-view

Custom linear layout


I'm trying to make my own LinearLayout to make it reusable and modular. first my code looked like this, which worked fine:

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);

Now i want to make my own LinearLayout class like this:

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) {

    }

}

my xml looks like this:

<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>

and use it like this:

mLlHeader = (Breadcrump)view.findViewById(R.id.ll_breadcrump);
....

EDIT

i now added the namespace in the layout xml file where i use my custom view and a new Constructor in the view class with an attribute set. Now the app starts. But it displays only my custom view and the rest of the layout is white ?


Solution

  • In your layout XML file, you probably have something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/ll_header"
        ... />
    

    Try changing it to

    <?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"
        ... />
    

    EDIT: how to use it in your activity?

    If your XML layout file is called main.xml, then just call setContentView(R.layout.main) in the onCreate() method of your activity. Your Breadcrump gets initialized internally. Then you can get a reference to it with (Breadcrump)view.findViewById(R.id.ll_header).