eg:
public class MainActivity extends BaseAppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout relativeLayoutRoot = new RelativeLayout(this);
relativeLayoutRoot.setBackgroundColor(Color.parseColor("#ffffff"));
RelativeLayout.LayoutParams relativeLayoutRootLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
relativeLayoutRoot.setLayoutParams(relativeLayoutRootLayoutParams);
LinearLayout linearLayoutNavigation = new LinearLayout(this);
linearLayoutNavigation.setBackgroundColor(Color.parseColor("#333333"));
LinearLayout.LayoutParams linearLayoutNavigationLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150);
linearLayoutNavigation.setLayoutParams(linearLayoutNavigationLayoutParams);
relativeLayoutRoot.addView(linearLayoutNavigation);
((RelativeLayout.LayoutParams)
linearLayoutNavigation.getLayoutParams()
).addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
for (int i = 0; i < 5; i++) {
RelativeLayout relativeLayoutNavigation = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeLayoutNavigationLayoutParams = new RelativeLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
relativeLayoutNavigation.setLayoutParams(relativeLayoutNavigationLayoutParams);
linearLayoutNavigation.addView(relativeLayoutNavigation);
((LinearLayout.LayoutParams) relativeLayoutNavigation.getLayoutParams()).weight = 1;
ImageView imageViewIcon = new ImageView(this);
imageViewIcon.setImageDrawable(getDrawable(R.drawable.tab_bar_message));
RelativeLayout.LayoutParams imageViewIconLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imageViewIcon.setLayoutParams(imageViewIconLayoutParams);
relativeLayoutNavigation.addView(imageViewIcon);
TextView textViewName = new TextView(this);
textViewName.setText("消息");
RelativeLayout.LayoutParams textViewNameLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewName.setLayoutParams(textViewNameLayoutParams);
textViewName.setTextColor(Color.parseColor("#ffffff"));
relativeLayoutNavigation.addView(textViewName);
((RelativeLayout.LayoutParams) imageViewIcon.getLayoutParams()).addRule(RelativeLayout.CENTER_IN_PARENT);
((RelativeLayout.LayoutParams) textViewName.getLayoutParams()).addRule(RelativeLayout.CENTER_HORIZONTAL);
Log.e(TAG, "onCreate: "+imageViewIcon.getId() );
// 此处不生效的原因是imageViewIcon.getId() 的值为-1
((RelativeLayout.LayoutParams) textViewName.getLayoutParams()).addRule(RelativeLayout.BELOW,imageViewIcon.getId());
}
setContentView(relativeLayoutRoot);
}
private static final String TAG = "MainActivity";
}
原因
不生效的原因是imageViewIcon.getId() 的值为-1
解决方案
给控件设置一个ID
imageViewIcon.setId(View.generateViewId());