【发布时间】:2014-03-25 13:56:03
【问题描述】:
我知道这个话题并不新鲜,但我真的被这个话题困住了,尝试了很多答案,但我仍然无法弄清楚我应该在哪里写和使用什么。
我有这个布局文件settings.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
...
<TextView
android:id="@+id/pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/pass_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="7dp"
android:text="Удалить пароль"
android:textAppearance="?android:attr/textAppearanceMedium" />
...
</LinearLayout>
我有TextView passdel,我想以编程方式添加。它的onCreate 描述是passdel=(TextView) findViewById(R.id.pass_del);
我有这些方法
public void onPasSet() {
pass.setText("Сменить пароль");
((LinearLayout)passdel.getParent()).addView(passdel);
}
public void onPasDel() {
pass.setText("Установить пароль");
((LinearLayout)passdel.getParent()).removeView(passdel);
}
onPasDel 运行良好。
我猜Java采用当前布局。所以当我删除View 时,它就在这个布局上。当我尝试添加这个View 时,Java 尝试在当前布局上找到这个视图,但它被删除了,所以..nullpointerexception。我应该如何正确地写所有addView 的东西?如何指向所需的布局?
【问题讨论】:
-
您希望
((LinearLayout)passdel.getParent()).addView(passdel);如何工作?如果您在某处添加passdel,可能是因为它没有父级,因此getParent只能返回null。你应该直接引用布局,给它一个 id。
标签: java android layout view add