Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND

Exploring LayoutInflater#inflate method | Android | V4ALL

Good day!!!


As a Android developer we all have experienced LayoutInflater#inflate at some point. But we maynot know clearly what this function will do. Come on, stay attention, Let's explore this in this blog with simple examples!!!

Let's assume you have a layout named fragment_first.xml as following
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <TextView
        android:id="@+id/textView"
        style="@style/TextAppearance.MaterialComponents.Headline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimary"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

And you have test_layout.xml as following
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonTest"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
As you know you can include the test_layout.xml programatically by following way
val testLayout = LayoutInflater.from(requireContext()).inflate(R.layout.test_layout, view as ConstraintLayout, true)
If you run the app, you will get following output.


As per LayoutInflater#inflate recieves following parameters.
resource
- int:ID for an XML layout resource to load (e.g., R.layout.main_page)
root
- ViewGroup: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.) This value may be null
attachToRoot
- boolean: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
and returns
View
- The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.
Ofcourse, the first parameter resource is easily understable and we know why this parameter is required and what should we passed.
But the second and third parameters are bit confusing, we are not clear what should we pass, in each condition what will happen. Let's explore this.

They are saying second parameter is optional, if third parameter is true, the first parameter will be child of second parameter. That's all, the second parameter is depend on third parameter, but its not necessory at all, but you can pass either true/false in third parameter at the same time you can pass rootview/null in second parameter, nothing will happen, app will not get crashed, no exception will be thrown.
But if you know this clearly, you can code easily on your requirement. If you want the first paramenter as child of your second parameter, note that the first parameter will be added based on your second parameter's LayoutParams For example, in the above layouts, both are constraint layout, and both has width and height as match_parent.

Let's set some background color for test_layout, ex:
android:background="@android:color/holo_orange_light"
Run the app, you will get following output.

Ofcourse the TextView is not visible in output, but note that, its accessible, see the toast which appeared tap on TextView.
Another example, let's change fragment_first.xml to LinearLayout and set orientation as vertical.
val testLayout = LayoutInflater.from(requireContext()).inflate(R.layout.test_layout, view as LinearLayout, true)
Run the app, you will get following output.

I hope, now you understand, why the second and third parameters required and what they are doing. If you have any doubts, please share as comment.

Also note that LayoutInflater#inflate returns a View, this is nothing but, if you pass second one as a layout and third parameter as true then its the current root view.

If you pass second one as null or third one as false, it is the root view of currently inflated layout, you can use it in RecyclerView, PopupWindow or some other component which expcets rootview as parameter.

Thank You, Share your thought as comments.

Comments

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.getText().toString(); et.setOnKeyListener(new OnKeyL

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i