项目中需要实现自定义控件,参照了网上的一些方法,实现了自己的需求,现在将实现过程简单做一下记录。
首先,上效果图:
图上的每一张图片加title都是自定义控件。
下面是实现过程:
1. 编写自定义控件的布局:
menu.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp"
android:orientation="vertical"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/iv_menu"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_list"
android:foreground="?android:attr/selectableItemBackground"/>
<TextView
android:textSize="18sp"
android:textColor="#000000"
android:id="@+id/tv_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="title"/>
</LinearLayout>
2. 编写对应的构造函数MenuLayout,继承LinearLayout(这个根据自己的实际布局设置)
public class MenuLayout extends LinearLayout {
private CircleImageView circleImageView;
private TextView textView;
public MenuLayout(Context context) {
super(context);
}
public MenuLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setGravity(Gravity.CENTER);
// 加载布局
LayoutInflater.from(context).inflate(R.layout.menu, this);
// 获取控件
circleImageView = (CircleImageView) findViewById(R.id.iv_menu);
textView = (TextView) findViewById(R.id.tv_menu);
}
// 为图片添加自定义点击事件
public void setOnclickImage(OnClickListener listener) {
circleImageView.setOnClickListener(listener);
}
// 设置标题的方法
public void setTitle(String title) {
textView.setText(title);
}
// 设置图片的方法
public void setImage(int iconImgId) {
circleImageView.setImageResource(iconImgId);
}
}
3. 然后在activity_main.xml中引用
<com.example.amap.View.MenuLayout
android:id="@+id/con_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"></com.example.amap.View.MenuLayout>
4. 最后在主函数中对控件进行实际操作:
public void InitMenu() {
MenuLayout menuLayout1 = (MenuLayout) findViewById(R.id.con_menu);
menuLayout1.setImage(R.drawable.ic_icon_list);
menuLayout1.setTitle("联系人");
menuLayout1.setOnclickImage(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (myAccount == null) {
FancyToast.makeText(getApplicationContext(), Language.notLogin, FancyToast.LENGTH_SHORT, FancyToast.WARNING, false).show();
} else {
Intent intent_contacts = new Intent(MainActivity.this, ContactsActivity.class);
intent_contacts.setAction("normal");
startActivity(intent_contacts);
}
}
});
}
最后的效果:
来源:CSDN
作者:lps11188
链接:https://blog.csdn.net/lps11188/article/details/104174664