I have mainActivity, that has xml that include another xml . Both activitymain layout has a button, and the included layout has another button. Both should display into the main activity. Now , i need to change text of both button. I can get reference to first button by findviewByID , and it works. for the second button that is into the second layout, i get view by inflating the layout, It gets properly refence to the view and the findviewbyID gets reference to this button. But when changing the text, it does not change.
activityMain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools">
<Button android:id="@+id/buttonvvv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
xmlns:android="http://schemas.android.com/apk/res/android" />
<include
layout="@layout/layouttest"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
layouttest.xml
<?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="match_parent">
<Button
android:id="@+id/buttonaaa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
---Mainactivity.java----------------------------------
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view=LayoutInflater.from(getApplication()).inflate(R.layout.layouttest, null);
Button b =(Button) findViewById(R.id.buttonvvv);
Button bb =(Button) view.findViewById(R.id.buttonaaa);
b.setText("ssssssss");
bb.setText("ssssssss");
}
Results
buttonvvv text is updated and becomes ssssssss
buttonaaa text is Not updated and still Button
You don't have to inflate the layout, just find it like:
LinearLayout layout =(LinearLayout) findViewById(R.id.layouttest);
and then
Button bb =(Button) layout.findViewById(R.id.buttonaaa);