Android Studio 3.1、Java 1.8。 私はプログラムでGridLayoutにビューを追加します。 私は方法addView()を使用します。アクティビティ:まず子供の親のremoveView()を呼び出す必要があります。
ここに私のアクティビティコード:
public class ProfileActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
private void init() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = getWindow().getDecorView().getRootView();
View profileCategoryActive = inflater.inflate(R.layout.profile_category_active, (ViewGroup) view, false);
TextView categoryNameTextView = profileCategoryActive.findViewById(R.id.categoryNameTextView);
for (int index = 0; index < categoryCount; index++) {
categoryNameTextView.setText("Hello " + index);
gridLayout.addView(profileCategoryActive);
}
}
}
しかし、私はランタイムエラーを取得:
FATAL EXCEPTION: main
Process: com.myproject.android.customer.debug, PID: 4929
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loyalix.android.customer.debug/com.loyalix.android.customer.ui.ProfileActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4309)