narb narb - 21 days ago 5
Android Question

How to add a TextView between Buttons

I'm trying on a button click to dynamically add a textview with comments associated with the button. I have a button A and B. I want(when I click on A) to add a text/TextView in between the button A and B.

Here is my xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>


<Button
android:id="@+id/a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="A"
/>

<Button
android:id="@+id/b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/a"
android:layout_marginTop="5dp"
android:text="B"
/>


<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test...."
android:visibility="invisible"
/>

</RelativeLayout>


Here is the code I tried:

public class MainActivity extends AppCompatActivity {


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

final Button a, b , c;
final TextView txt;
final RelativeLayout layout;

layout = (RelativeLayout) findViewById(R.id.layout);
a = (Button) findViewById(R.id.a);
b = (Button) findViewById(R.id.b);
txt = (TextView) findViewById(R.id.txt);


a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
p.addRule(RelativeLayout.BELOW, a.getId());
layout.addView(txt, p);
setContentView(layout);
}
});

}

}


I have the following error message: The specified child already has a parent. You must call removeView() on the child's parent first.

Answer

1) You can change RelativeLayout to LinearLayout

2) Move TextView between Buttons and set visible GONE.

3) onClick() -> setVisibility to View.VISIBLE.

hope to help you.