public class ContextCompat{}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
relativeLayout.addView(linearLayout);
for (int i = 0; i < 3; i++) {
ImageView imageView = new ImageView(this);
// 过时
// imageView.setImageDrawable(getDrawable(R.drawable.android));
// 替代方法
imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.firefox));
TextView textView = new TextView(this);
textView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_orange_dark));
textView.setText(String.valueOf(i));
imageView.setId(i);
textView.setId(i);
linearLayout.addView(imageView);
linearLayout.addView(textView);
imageView.setOnClickListener(this);
textView.setOnClickListener(this);
}
}
@Override
public void onClick(View v) {
String idinfo = "";
switch (v.getId()) {
case 1:
idinfo = "Button1";
break;
case 2:
idinfo = "Button2";
break;
case 0:
idinfo = "Button1";
break;
}
Toast.makeText(this, idinfo, Toast.LENGTH_SHORT).show();
}
}
0 件のコメント:
コメントを投稿