LayoutInflate & LayoutParams (tip)
一、LayoutInflate
除过setContentView()用于Activity加载布局,就要使用LayoutInflate
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null);
详解:Android 通过Java代码生成创建界面。动态生成View,动态设置View属性。addRules详解
二、LayoutParams
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(100,100);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
注:单位是px
public class MainActivity extends Activity implements View.OnClickListener{
private static final String TAG = "MainActivity";
private LinearLayout ll_one;
private HashMap<Integer, Button> btnMap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnMap = new HashMap<Integer, Button>();
ll_one = findViewById(R.id.ll_one);
for (Integer i = 0; i < 6; i++) {
Button button1 = new Button(ll_one.getContext());
button1.setText("button"+i);
button1.setTag(i);
button1.setTextColor(Color.GREEN);
button1.setOnClickListener(this);
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(300, 120);
button1.setLayoutParams(btnParams);
ll_one.addView(button1);
btnMap.put(i,button1);
}
}
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: "+view.getTag());
Button button = btnMap.get((Integer) view.getTag());
button.setBackgroundColor(Color.RED);
switch ((Integer) view.getTag()){
case 0:
Log.d(TAG, "ss onClick: "+view.getTag());
break;
case 1:
Log.d(TAG, "ss onClick: "+view.getTag());
break;
case 2:
Log.d(TAG, "ss onClick: "+view.getTag());
break;
}
}
}
网友评论