2016-07-29 50 views
0

我想插入一些LinearLayouts,但它不能像它應該那樣工作。它只插入一個,但它應該插入更多。用不同的值插入佈局

LinearLayout commentsContainer = (LinearLayout) findViewById(R.id.view_comment_container); 
        commentsContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
        commentsContainer.setOrientation(LinearLayout.HORIZONTAL); 
        for (int i = 0; i < postView.commentLenght(); i++) { 
         Log.e("LENGTH", postView.commentLenght()+"x"+i); 
         LinearLayout commentContainer = new LinearLayout(PostViewActivity.this); 
         commentContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
         LinearLayout userContainer = new LinearLayout(PostViewActivity.this); 
         userContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
         userContainer.setOrientation(LinearLayout.VERTICAL); 
         commentContainer.setOrientation(LinearLayout.HORIZONTAL); 
         commentContainer.setPadding(25,0,0,0); 
         ImageView commentImage = new ImageView(PostViewActivity.this); 
         commentImage.setLayoutParams(new LinearLayout.LayoutParams((int) ((float) width/6), (int) ((float) width/6))); 
         commentImage.setImageBitmap(postView.getComment(i).getImage()); 
         TextView commentText = new TextView(PostViewActivity.this); 
         commentText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
         commentText.setText(postView.getComment(i).getText()); 
         TextView displayUserText = new TextView(PostViewActivity.this); 
         displayUserText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
         displayUserText.setText(postView.getComment(i).getDisplayName()); 
         Log.d("TEXT", postView.getComment(i).getText()); 
         Log.e("TEXT", displayUserText.getText()+""); 
         displayUserText.setTag(postView.getComment(i).getUsername()); 
         displayUserText.setTextSize(12); 
         displayUserText.setTextColor(getResources().getColor(R.color.colorAccent)); 
         userContainer.addView(commentImage); 
         userContainer.addView(displayUserText); 
         commentContainer.addView(userContainer); 
         commentContainer.addView(commentText); 
         commentsContainer.addView(commentContainer); 

        } 

另一個奇怪的事情是:第一個Log.d總是正確的,但第二個總是相同的。什麼是錯誤?

回答

1

通過使用XML資源文件可以大大地清除此代碼。由於每個註釋採用相同的形式,因此每個註釋都可以使用相同的佈局。您可以根據需要在佈局中填入不同的值。這些都可以添加到另一個佈局中的ViewGroup。

以編程方式生成佈局比使用XML佈局更容易出錯和複雜。

做一些閱讀Android官方文檔是絕對值得的! https://developer.android.com/guide/topics/ui/declaring-layout.html

+0

謝謝!是的,這真的很好:-) – user6586661