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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With