gpt4 book ai didi

android - 使用 View 多次充气

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:00 25 4
gpt4 key购买 nike

我在膨胀和重新使用同一个 TextView 方面遇到了一些问题。
就像它试图一遍又一遍地覆盖相同的 TextView 之类的,但它不能那样做?

LayoutInflater inflater = LayoutInflater.from(this);
View mainlayout = inflater.inflate(R.layout.days_monday_inflate, null);
View layout_number = inflater.inflate(R.layout.inflate_number, null);

for (int i = 0; i < 10; i++) {
row = new TableRow(this);
number = (TextView) layout_number.findViewById(R.id.Number);
number.setTag(i);
number.setText(Integer.toString(i));
row.addView(number);
}
setContentView(mainlayout);

这是 inflate_number.xml

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Number"
android:layout_width="3dp"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
android:text="1" />

这是我收到的错误,它位于第 51 行,即: row.addView(number);



<p><code></code></p><code>

</code><pre><code>07-18 20:54:25.124: E/AndroidRuntime(1166): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.view.ViewGroup.addViewInner(ViewGroup.java:1970)
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.view.ViewGroup.addView(ViewGroup.java:1865)
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.view.ViewGroup.addView(ViewGroup.java:1822)
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.view.ViewGroup.addView(ViewGroup.java:1802)
07-18 20:54:25.124: E/AndroidRuntime(1166): at com.trainingschedule.days.Monday.onCreate(Monday.java:50)
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-18 20:54:25.124: E/AndroidRuntime(1166): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
</code></pre>

最佳答案

您实际上从未向您的 Activity 添加任何 View 。您正在创建新的 TableRows 并将 TextViews 添加到它们,但您永远不会将行添加到任何东西。假设您在 R.layout.days_monday_inflate 中有一个 TableLayout,您应该首先获取对该 View 的引用 (TableLayout layout = (TableLayout)mainLayout.findViewById(R.id.my_table_layout_id)),然后将每一行添加到该 TableLayout:

TableLayout layout = (TableLayout)mainLayout.findViewById(R.id.my_table_layout_id);

for(int i = 0; i < 10; i++) {
row = new TableRow(this);
View layout_number = inflater.inflate(R.layout.inflate_number, layout, false);
TextView number = (TextView) layout_number.findViewById(R.id.Number);
number.setTag(i);
number.setText(Integer.toString(i));
row.addView(number);
layout.addView(row);
}

尽管我建议尽可能使用 XML 完全设置您的布局,除非动态需要。另外,如果您每行只添加一个 TextView,我建议您最好只使用 LinearLayout。

关于android - 使用 View 多次充气,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11550346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com