2017-12-20 8 views
0

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) 

答えて

1

あなたは...

for (...) { 
    // can't add _same_ view multiple times! 
    gridLayout.addView(profileCategoryActive); 
} 

ビューを複数回同じビューを追加しています1つの親のみを持つことができます/他の1つのビューに追加することができます。


複数のビューをレイアウトに追加する場合は、複数のビューを展開し、それぞれ別々に追加する必要があります。

for (...) { 
    View view = inflate(..) // inflate new view 
    layout.addView(view); // add new view 
} 
1

エラーメッセージは自己診断です。

if(profileCategoryActive.getParent()!=null) 
((ViewGroup)profileCategoryActive.getParent()).removeView(profileCategoryActive); // Remove view 
gridLayout.addView(profileCategoryActive); 
関連する問題