Nat
Nat

Reputation: 908

Use layout XML to create button

I've defined a layout in XML and now I'd like to use it to make a custom button (It just has to show the layout and be clickable, I don't care about different states and stuff). I'm not too sure what to do next though. How to I create this in my main activity?

Thanks!

My custom XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="25dp"
    android:layout_marginTop="10dp"
    android:textSize="20dp"
    android:text="New Text"
    android:id="@+id/text" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginRight="25dp"
    android:layout_alignParentRight="true"
    android:src="@drawable/left"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"
    android:maxHeight="30dp"
    android:maxWidth="30dp"/>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/text"
    android:height="1dp"
    android:background="@color/dim_foreground_material_dark"
    android:layout_marginLeft="25dp"
    android:layout_marginTop="10dp"
    android:text=""
    android:id="@+id/horiz" />
</RelativeLayout>

Upvotes: 1

Views: 86

Answers (2)

Nat
Nat

Reputation: 908

Figured it out, I can reference the layout in XML by using an <include/> tag.

<include layout="@layout/settings_layout"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/accountStaticUnderline"
    android:id="@+id/termBegin"/>

Upvotes: 0

user5703518
user5703518

Reputation:

Lets start by exploring how we can create custom view:

1)Subclass one of the built-in layouts.

2)Inflate a merge layout in the constructor.

3)Initialize members to point to inner views with findViewById().

4)Add your own APIs to query and update the view state.

So I think you want to use the second option:

public class ButtonView extends Button  {

    public ButtonView (Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ButtonView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        LayoutInflater.from(context).inflate(R.layout.custom_xml, this, true);

    }


}

for further reading take a look at:

Custom Layouts on Android

Upvotes: 1

Related Questions