Android自定义组件

时间:2023-03-08 23:04:28
Android自定义组件

[参考的原文地址]

http://blog.csdn.net/l1028386804/article/details/47101387

效果图:

Android自定义组件

实现方式:

一:自定义一个含有EditText和Button的组件

先创建一个buttonext_layout的自定义组件的XML布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:inputType="text"/>
<Button
android:id="@+id/clearButton"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Clear"/> </LinearLayout>

二:创建自定义控件类ButExt

public class ButExt extends LinearLayout {
private EditText mEditText;
private Button mButton; public ButExt(Context context) {
super(context);
//使用布局资源填充视图
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//加载布局文件
mInflater.inflate(R.layout.buttonext_layout, this, true);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.clearButton);
hookupButton(context); } /**
* button处理程序
*/
private void hookupButton(final Context context) {
mButton.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
mEditText.setText("");
Toast.makeText(context, "文本框数据已清除", Toast.LENGTH_SHORT).show();
}
});
}
/**
*给EditText赋值
*/
    public void setText(String txt){
mEditText.setText(txt);
}
}

三:MainActivity类的实现

public class MainActivity extends AppCompatActivity {
private LinearLayout mLinearLayout; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//动态的添加我们自定义的组件
mLinearLayout = (LinearLayout) findViewById(R.id.main_layout);
for (int i = 0; i < 3; i++) {
imageViewExt editText = new imageViewExt(this);
editText.setText(i+");
mLinearLayout.addView(editText);
}
}
}