A composite control combines several existing controls of the system to form a composite control. For example, the title bar with a return button is the simplest Composite Control. The advantage of using composite controls is to improve code reusability and to use multiple definitions in one place. Below we will use a combination of controls to achieve this effect:
First, we need to customize a view:
Package com. example. widgets; import android. app. activity; import android. content. context; import android. util. attributeSet; import android. view. layoutInflater; import android. view. view; import android. view. view. onClickListener; import android. widget. frameLayout; import android. widget. imageButton; import android. widget. textView; import com. example. viewdemo4.R;/*** @ author Rowand jj * Custom title bar component */public class TitleBar extends FrameLayout implements OnClickListener {private ImageButton ib_ret = null; private TextView TV _show = null; public TitleBar (Context context) {super (context);} public TitleBar (Context context, AttributeSet attrs) {super (context, attrs, 0); LayoutInflater inflater = LayoutInflater. from (context); inflater. inflate (R. layout. title, this); // specify the filled xml layout file and the root view ib_ret = (ImageButton) findViewById (R. id. ib_ret); TV _show = (TextView) findViewById (R. id. TV _show); ib_ret.setOnClickListener (this) ;}@ Override public void onClick (View v) {if (this. getContext () instanceof Activity) {Activity a = (Activity) this. getContext ();. finish () ;}} public void setTitleText (CharSequence text) {this. TV _show.setText (text);} public void setLeftButListener (OnClickListener listener) {this. ib_ret.setOnClickListener (listener );}}In this custom view, we load a custom layout as follows:
The background of the button on the left is an image that references a selector file:
In this way, the combined control is ready. Next we will use this composite control on activity. First, we need to specify the control we define on the layout:
Just like using a common control. MainActivity:
Package com. example. viewdemo4; import android. app. activity; import android. OS. bundle; import com. example. widgets. titleBar; public class MainActivity extends Activity {private TitleBar title_bar = null; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); title_bar = (TitleBar) findViewById (R. id. title_bar); title_bar.setTitleText ("about Author ");}}You can modify the text displayed by the widget and the Click Event of the buttons on the left.