Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom View with XML Layout in Android

I have a ListAdapter with a lot of different layouts for the rows. To have a clean code I want to outsource the layouts for the rows from the getView() of the adapter in View classes. Is it possible to inflate a XML layout into a custom view? I've only found the LayoutInflater but it returns a View and that does not help. I want to have something like the setLayout() of an Activity. Is this possible?

Thanks!

like image 471
dbrettschneider Avatar asked Apr 04 '11 06:04

dbrettschneider


People also ask

Can you a create custom view how Android?

Creating custom views. By extending the View class or one of its subclasses you can create your custom view. For drawing view use the onDraw() method. In this method you receive a Canvas object which allows you to perform drawing operations on it, e.g. draw lines, circle, text or bitmaps.

What is a custom view Android?

A well-designed custom view is much like any other well-designed class. It encapsulates a specific set of functionality with an easy to use interface, it uses CPU and memory efficiently, and so on. In addition to being a well-designed class, though, a custom view should: Conform to Android standards.

What is Android XML layout?

Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. You can also use Android Studio's Layout Editor to build your XML layout using a drag-and-drop interface. Instantiate layout elements at runtime.

What are the types of custom views?

In Android, there are actually two other Views readily available to do this: Spinner and AutoCompleteTextView , but regardless, the concept of a Combo Box makes an easy-to-understand example.


1 Answers

You can have a custom row view and inflate your xml in its constructor:

public MyRow extends LinearLayout {
    public MyRow(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.my_row, this, true);
          ... other initialization ...
    }
}

and then use merge in my_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
  ... your row layout ...
</merge>

The merge element causes its children to be added as children of your custom view. Check out Merging Layouts for more info.

like image 58
Matthew Willis Avatar answered Oct 21 '22 21:10

Matthew Willis