package com.example.lesson4_dynamic;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
Random random = new Random();
for (int j = 0; j < 10; j++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 0, j + 10);
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
TextView textView = new TextView(this);
textView.setLayoutParams(params);
int color = Color.rgb(r, g, b);
textView.setBackgroundColor(color);
layout.addView(textView);
}
setContentView(layout);
}
}
“`
package com.example.lesson4_dynamic;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
Random random = new Random();
for (int j = 0; j < 30; j++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 0, j + 10);
int r = random.nextInt(256);
// int g = random.nextInt(256);
// int b = random.nextInt(256);
TextView textView = new TextView(this);
textView.setLayoutParams(params);
int color = Color.rgb(r, r,r+j);//此处不安全数组会越界
textView.setBackgroundColor(color);
layout.addView(textView);
}
setContentView(layout);
}
}
“`