TextView textView = new TextView(MainActivity.this);
//设置LayoutParams 否则会空指针异常 textView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); if(i==0){ textView.setBackgroundColor(getResources().getColor(R.color.red)); }else { textView.setBackgroundColor(getResources().getColor(R.color.gray)); } textView.setText((i+1)+""); textView.setGravity(Gravity.CENTER); textView.setWidth(30); textView.setWidth(30);
//在获取LayoutParams之前要设置LayoutParams 否则会空指针异常 LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) textView.getLayoutParams(); lp.setMargins(10, 10, 10, 10); textView.setLayoutParams(lp); textView.setTextColor(getResources().getColor(R.color.white));