我正在尝试使用按钮单击以动态添加与该按钮关联的注释的textview。我有一个按钮A和B.我想要的(当我点击A)在按钮A和B.如何在按钮之间添加TextView
这里之间添加一个文本/ 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()。
您尝试添加的TextView这已经是你的RelativeLayout。你的目的是什么?移动textview或添加新的textview? –
这很令人困惑,我同意。我的目标是添加一个新文本。你可以从XML中移除TextView。如果TextView实例已经存在,我认为它会更简单。 – narb
为什么不把它作为'去'(可见性)添加到布局中并且将其显示/隐藏到代码中?这很容易,你不需要以编程方式创建它,以实现我将要做的那个 –