自定义LinearLayout

日常开发中,类似图片的布局非常常见,如果每次都要使用linearLayout或者其他布局包含子控件去实现的话,代码重复量大,所以我们可以用自定义布局去实现。
自定义LinearLayout
文章图片
方法一
1.新建一个布局文件item_ly.xml


1.新建一个类MyLinearLayout.java
public class MyLinearLayout { private Activity activity; private LyClickListener lyClickListener; private TextView selectTV; private TextView contentTV; public interface LyClickListener{ void clickLy(View view); }public void init(Activity activity,String content){ this.activity = activity; selectTV = (TextView) activity.findViewById(R.id.select); contentTV = (TextView) activity.findViewById(R.id.content); }public void setClickEvent(LyClickListener lyListener){ lyClickListener = lyListener; selectTV.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(lyClickListener != null){ lyClickListener.clickLy(v); } } }); }public void setData(String msg){ if(selectTV != null){ selectTV.setText(msg); } } }

3.使用方法
1>在activity_main.xml中include

2>在MainActivity.java中

MyLinearLayout myLinearLayout = new MyLinearLayout(); //给左边赋值 myLinearLayout.init(MainActivity.this,"城市"); myLinearLayout.setClickEvent(new MyLinearLayout.LyClickListener() { @Override public void clickLy(View view) { //点击的时候改变右边的数据 myLinearLayout.setData("西安"); } });

方法二
1.新建布局文件item_ly.xml(参照方法一)
2.自定义LinearLayout:
public class SelectLinearLayout extends LinearLayout { private TextView content; private TextView select; public SelectLinearLayout(Context context) { super(context); }public SelectLinearLayout(Context context, @Nullable AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.item_ly, this); content = (TextView) findViewById(R.id.content); select = (TextView) findViewById(R.id.select); }public void setContent(String food){ if(content != null){ content.setText(food); } }public void setData(String food){ if(select != null) { select.setText(food); } } }

3.在activity_main.xml里面写布局:

【自定义LinearLayout】4.在MainActivity.java中使用:
SelectLinearLayoutselectLinearLayout = (SelectLinearLayout) findViewById(R.id.food_ly); selectLinearLayout.setContent("食品"); //给左边赋值 //点击改变右边的值 selectLinearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectLinearLayout.setData("米饭"); } });

    推荐阅读