5
votes

I'm learning android and wonder why I can't find the real purpose of the attribute tools:context in layout XML file.

I read here https://developer.android.com/studio/write/tool-attributes.html#toolscontext under the image that onClick will not work for any View until we specify tools:context.

I tried and wonder it is working without any tools:context I also read from the stackoverflow that it used to choose proper theme for the layout. But it is working fine for me without using tools:context then what is the real purpose of this?

XML Layout:

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

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="CallIt"
        />
</RelativeLayout>

Main Activity:

package com.something.testingwith42;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void CallIt(View view){
        Toast.makeText(this, "Checking", Toast.LENGTH_LONG).show();
    }
}

Everything is working fine without tools:context

1

1 Answers

9
votes

onClick will not work for any View until we specify tools:context

There is nothing in that documentation that makes that claim.

Everything is working fine without tools:context

Correct. That is because that is nothing in that documentation that states that onClick() will only work if you have tools:context. It does say that for quick-fixes, you need tools:context for the tools to know where to add the onClick() method.

also read from the stackoverflow that it used to choose proper theme for the layout

This too is incorrect.

What is the real purpose of tools:context in Android XML

It provides context for development tools, as to where this layout will be used, so that the tools can provide better assistance to developers, such as:

  • more accurate rendering of previews, taking the hosting activity and its theme into account
  • more intelligent assistants, such as the aforementioned quick-fixes

tools:context is completely optional. Development tools can and do work without it. Those tools may provide somewhat degraded assistance to you, but that is your choice.

tools:context — or any attribute in the tools namespace — will have no impact at runtime. I have not checked, but I would hope that they even get stripped out when packaging the APK, as they have no use at runtime.