您的位置:首页 > 移动开发 > Android开发

android在代码中怎么使得控件居中,以及代码设置控件selector

2016-07-25 16:36 459 查看
      最近在做一个项目,分别是登录前的状态,和登录后的状态,LinearLayout背景颜色和高度需要改变,LinearLayout布局中的TextView字体需要改变,ImageView控件要改变,原来是居中显示的,那么改变控件后,还想要居中,只需要在xml中设置android:layout_gravity="center"属性即可。

       ImageView控件的图片,点击和不点击有两种状态,在代码中设置和xml中android:background="@drawable/xxxx" 的效果。

  

/**
*    xml的selector对应的java代码设置
* */
private StateListDrawable addStateDrawable(Context context,  int idNormal, int idPressed, int idFocused) {
StateListDrawable sd = new StateListDrawable();
Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal);
Drawable pressed = idPressed == -1 ? null : context.getResources().getDrawable(idPressed);
Drawable focus = idFocused == -1 ? null : context.getResources().getDrawable(idFocused);
//注意该处的顺序,只要有一个状态与之相配,背景就会被换掉
//所以不要把大范围放在前面了,如果sd.addState(new[]{},normal)放在第一个的话,就没有什么效果了
//sd.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, focus);
//sd.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
//sd.addState(new int[]{android.R.attr.state_focused}, focus);
sd.addState(new int[]{android.R.attr.state_pressed}, pressed);
sd.addState(new int[]{android.R.attr.state_enabled}, normal);
sd.addState(new int[]{}, normal);
return sd;
}


调用处:

loginOrRegister_iv.setBackgroundDrawable(addStateDrawable(this, R.mipmap.logined ,R.mipmap.logined_pressed ,R.mipmap.logined_pressed ));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  控件 智慧酒店