Boby Siwonhansamu Boby Siwonhansamu - 16 days ago 5
Android Question

How to include same layout twice programmatically in android?

i have trouble to call layout programmatically, i try in xml using include and its work

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/btnTes"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/LL1"
android:orientation="vertical">

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

<include layout="@layout/extend">

</include>

</LinearLayout>




but i want create it programmatically
this is my extend XML :

<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />

<TextView
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2" />




and this is my java :

public class MainActivity extends AppCompatActivity {
Button btnTes;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
btnTes = (Button) findViewById(R.id.btnTes);
final View extend = LayoutInflater.from(this).inflate(R.layout.extend,null);

btnTes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
tes.addView(extend);

}
});

}


}

when i click btnTes
for the first clicked its ok, but when i click it again my program just force close. This is my error

FATAL EXCEPTION: main
Process: com.example.siwonhansamu.test, PID: 3796
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.


Thanks

Answer

You can't add the same view to multiple parents.

You have to do a copy of the view if you want it multiple times. You could do like this :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
    btnTes = (Button) findViewById(R.id.btnTes);

    btnTes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
            final View extend = LayoutInflater.from(view.getContext()).inflate(R.layout.extend, tes, false);
            tes.addView(extend);

        }
    });
}
Comments