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

android 自定义组合控件

2015-12-22 18:11 579 查看
自定一个类似的view  -------作为ListView的条目



那就要自定义如下的item



* 自定义控件
* 1、写layout布局文件
* 2、在java代码中定义一个类继承 RelativeLayout
* 3、重写它的三个  构造方法( 三个构造方法的具体含义可以百度)
* 4、View.inflate() 将layout的布局文件 填充成一个view
* 5、利用RelativeLayout的addView(view)方法将我的布局文件的填充出来的view加入到里面就可以了
* 6、编写一些自定义的 方法来操作 该自定view

在三个构造方法中都调用一次

public void  initView(Context context){
view = View.inflate(context, R.layout.item_friend_state, null);
ivUserIcon = (ImageView) view.findViewById(R.id.iv_userIcon);//用户头像
tvUserName = (TextView) view.findViewById(R.id.tv_userName);//用户名
ivUserState = (ImageView) view.findViewById(R.id.iv_userState);//在线状态图标
tvUserState = (TextView) view.findViewById(R.id.tv_userState);//用户在线状态
ivUserTermianl = (ImageView) view.findViewById(R.id.iv_userTerminal);//用户使用的终端图标
addView(view);
}


关键就是 intflate()  和  addView()方法    这是将布局文件和java代码关联起来的关键

然后写一些操作view的方法

public class ContactItemView extends RelativeLayout {
private View view;
private ImageView ivUserIcon;
private TextView tvUserName;
private ImageView ivUserState;
private TextView tvUserState;
private ImageView ivUserTermianl;

public ContactItemView(Context context) {
super(context);
initView(context);
}

public ContactItemView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}

public ContactItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}

public void initView(Context context){ view = View.inflate(context, R.layout.item_friend_state, null); ivUserIcon = (ImageView) view.findViewById(R.id.iv_userIcon);//用户头像 tvUserName = (TextView) view.findViewById(R.id.tv_userName);//用户名 ivUserState = (ImageView) view.findViewById(R.id.iv_userState);//在线状态图标 tvUserState = (TextView) view.findViewById(R.id.tv_userState);//用户在线状态 ivUserTermianl = (ImageView) view.findViewById(R.id.iv_userTerminal);//用户使用的终端图标 addView(view); }
//设置用户的头像
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setUserIcon(Drawable background){
ivUserIcon.setBackground(background);
}
//设置 用户名
public void setUserName(String userName){
tvUserName.setText(userName);
}
//设置用户的在线状态图标
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setUserStateIcon(Drawable background){
ivUserState.setBackground(background);
}
//设置用户的在线状态的文字描述
public void setUserStateDescr(String stateDescr){
tvUserState.setText(stateDescr);

}
//设置用户的用的终端图标
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void setIvUserTermianl(Drawable background){
ivUserTermianl.setBackground(background);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android