自定义控件
点击Button,EditText里的字会清空
MainActivity:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent" 4 android:orientation="vertical" > 5 6 <com.example.canvastest.MyView 7 android:layout_width="match_parent" 8 android:layout_height="0dp" 9 android:layout_weight="1" /> 10 11 </LinearLayout>
1 public class MainActivity extends Activity { 2 public static final String TAG = "MainActivity"; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 } 9 }
MyView:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <EditText 8 android:id="@+id/edt" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" /> 11 12 <Button 13 android:id="@+id/btn" 14 android:layout_width="match_parent" 15 android:layout_height="wrap_content" 16 android:text="clear" /> 17 18 </LinearLayout>
1 public class MyView extends LinearLayout implements View.OnClickListener { 2 private EditText edt; 3 private Button btn; 4 5 public MyView(Context context, AttributeSet attrs) { 6 super(context, attrs); 7 8 LayoutInflater inflater = (LayoutInflater) context 9 .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 10 View view = inflater.inflate(R.layout.myview, this); 11 12 edt = (EditText) view.findViewById(R.id.edt); 13 14 btn = (Button) view.findViewById(R.id.btn); 15 btn.setOnClickListener(this); 16 } 17 18 @Override 19 public void onDraw(Canvas canvas) { 20 super.onDraw(canvas); 21 } 22 23 @Override 24 public void onClick(View v) { 25 switch (v.getId()) { 26 case R.id.btn: 27 edt.setText(""); 28 break; 29 } 30 } 31 }