在XML文件中,我创建了TextView。比我想要从代码
添加到Activity<TextView
android:id="@+id/letter_cell"
android:gravity="center"
android:layout_weight="1"
android:text="1"
/>
MainActivity
LayoutInflater inflater = (LayoutInflater)getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View table_pattern = inflater.inflate(R.layout.letters_table, null);
TextView txt_row = (TextView) table_pattern.findViewById(R.id.letter_cell);
LinearLayout linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
setContentView(linLayout, linLayoutParam);
linLayout.addView(txt_row);
运行应用后,我收到了一些错误
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
答案 0 :(得分:0)
您正在从一个视图中获取元素(TextView
中的R.layout.letters_table
)并尝试将其添加到LinearLayout
。您必须添加整个膨胀的视图或以编程方式创建TextView
。视图只能有一个父级,并且会在您尝试添加到另一个视图时抛出您看到的异常。
答案 1 :(得分:0)
txt_row
textView已经拥有父级,因为它位于table_pattern
内。你需要:
首先将其从父项中删除:
table_pattern.removeView(txt_row);
linLayout.addView(txt_row);
两者都应该有用。希望它有所帮助!