Joshua Best
Joshua Best

Reputation: 246

Making a textview global

I am wondering if there is any way that you can make a textview visible over every screen so that I don't have to individually create a textview on every activity.

I want to do this so I can display my application version on every screen for debugging.

Thank you.

Upvotes: 0

Views: 132

Answers (1)

Khemraj Sharma
Khemraj Sharma

Reputation: 58974

Yes! it is possible.

See you have to add this code.

<include layout="@layout/layout_version"/>

and

public class MainActivity extends BaseActivity {

}

And you will find version text.

Just add this few code.

(1) Create a layout that will represent version text.

layout_version.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" // or match_parent (according to your need)
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvVersion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ... other properties
        />

    <!--... other component if required-->

</LinearLayout>

(2) Include this to your activity layout like activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   ...>

    <include layout="@layout/layout_version"/>

</LinearLayout>

(3) Create a BaseActivity.class or add my code if you have already.

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.innovanathinklabs.sample.BuildConfig;
import com.innovanathinklabs.sample.R;

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tvVersion = findViewById(R.id.tvVersion);
        if (tvVersion != null) tvVersion.setText(BuildConfig.VERSION_NAME);
    }
}

(4) Final step is to extend all your activity by BaseActivity.class.

public class MainActivity extends BaseActivity {

}

That's all!

Upvotes: 2

Related Questions