简体   繁体   中英

How to change the gravity of a TextView in another xml file from Main Activity?

I have an XML file that has a TextView , and I want to change its gravity from the main activity.
I used this code in the main activity:

// I just coppied the related codes 

TextView tvValue;

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

    tvValue = findViewById(R.id.tv_value); 

    // the tv_value id is from the (word_item.xml) file

}

private void OnClickFunc(View view) {
    tvValue.setGravity(Gravity.RIGHT);
}

and the problem is that I get a NullPointerException error on a null object reference .
I know that I should somehow connect the xml file with the main activity.

word_item.xml file:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">

  <TextView
    android:id="@+id/tv_value"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Word" />

</LinearLayout>

Thank you and I appreciate your help.

if you havent included the word_item.xml in your activity_main.xml then the error is obvious

so this is how you can include another file in any xml file in android

<include layout="@layout/word_item.xml" />

then things ll work as you expect

Try to first inflate the other layout as follows the initialize the view

LayoutInflater inflater = LayoutInflater.from(MainActivity.this); final View v = inflater.inflate(R.layout.word_item, null);

Then

Textview tvValue = findViewById(R.id.tv_value); private void OnClickFunc() { tvValue.setGravity(Gravity.RIGHT);

Where did you initialize textView variable?? Variable must be initialize after setContentView in OnCreate method in Activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM