私はボタンをクリックして、ボタンに関連付けられたコメント付きのテキストビューを動的に追加しようとしています。私は(私はAをクリックしたとき)、私はボタンAとの間でテキスト/のTextViewを追加したいボタンAとBを持っているし、ここでB.ボタンの間にTextViewを追加する方法
は私のxmlファイルです:
<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>
ここれます私が試したコード:
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);
}
});
}
}
私は、次のエラーメッセージがあります:指定された子は、すでに親を持っています。子の親で最初にremoveView()を呼び出す必要があります。
であなたのRelativeLayoutにすでにあるのTextViewを追加しようとしている、それを試してみてください。あなたの目的はなんですか?テキストビューの移動または新しいテキストビューの追加? –
それは混乱している、私は同意する。私の目標は、新しいテキストを追加することです。 XMLからTextViewを削除することができます。 TextViewインスタンスが既に存在していた方が簡単だろうと思っていました。 – narb
レイアウトに「表示されません」(可視性)として追加し、コードから表示/非表示にするのはなぜですか?それは簡単です、私はそれを達成するためにプログラムでそれを作成する必要はありません –