王学岗动态生成控件ID

在代码中动态设置控件,如果你不给控件设置ID,默认是没有ID的。
动态设置代码ID如下

 RelativeLayout relativeLayout = new RelativeLayout(mContext);
 TextView textView = new TextView(mContext);
 textView.setId(View.generateViewId());//动态设置ID
 relativeLayout.addView(textView);
        TextView textToday = new TextView(mContext);
        RelativeLayout.LayoutParams relativeLayoutParams2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayoutParams2.addRule(RelativeLayout.CENTER_HORIZONTAL);
        relativeLayoutParams2.addRule(RelativeLayout.BELOW,textView.getId());//代码中使用

注意,如果textView没有调用

textView.setId(View.generateViewId());//动态设置ID

那么

    relativeLayoutParams2.addRule(RelativeLayout.BELOW,textView.getId());//代码中使用

不会生效

你可能感兴趣的:(随笔,android)