你的位置:首页 > 操作系统

[操作系统]Android 自定义控件的使用


首先自定义一个attrs.

<??><resources>  <declare-styleable name="TopBar">    <attr name="titleText" format="string"></attr>    <attr name="titleTextSize" format="dimension"></attr>    <attr name="titleTextColor" format="reference|color"></attr>    <attr name="leftButtonText" format="string"></attr>    <attr name="leftButtonTextSize" format="dimension"></attr>    <attr name="leftButtonBackground" format="reference|color"></attr>    <attr name="rightButtonText" format="string"></attr>    <attr name="rightButtonTextSize" format="dimension"></attr>    <attr name="rightButtonBackground" format="reference|color"></attr>  </declare-styleable></resources>

 

自定义类TopBar,为简单起见 继承RelativeLayout

package com.sphere.topbar;import android.annotation.SuppressLint;import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast;public class TopBar extends RelativeLayout {  private String titleText;  private float titleTextSize;  private int titleTextColor;  private String leftButtonText;  private float leftButtonTextSize;  private Drawable leftButtonBackground;  private String rightButtonText;  private float rightButtonTextSize;  private Drawable rightButtonBackground;  private TextView titleTextView;  private Button leftButton;  private Button rightButton;  private LayoutParams titleLayoutParams;  private LayoutParams leftBtnLayoutParams;  private LayoutParams rightBtnLayoutParams;  private TopBarOnClickListener listener;  // 定义点击响应事件回调接口  interface TopBarOnClickListener{    public abstract void onLeftButtonClicked();    public abstract void onRightButtonClicked();  }  @SuppressLint("NewApi")  public TopBar(Context context, AttributeSet attrs) {    super(context, attrs);    // 得到    TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.TopBar);    // 得到title的各个属性    titleText = ta.getString(R.styleable.TopBar_titleText);    titleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, 0);    titleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);    // 得到left button的各个属性    leftButtonText = ta.getString(R.styleable.TopBar_leftButtonText);    leftButtonTextSize = ta.getDimension(R.styleable.TopBar_leftButtonTextSize, 0);    leftButtonBackground = ta.getDrawable(R.styleable.TopBar_leftButtonBackground);    // 得到right button的各个属性    rightButtonText = ta.getString(R.styleable.TopBar_rightButtonText);    rightButtonTextSize = ta.getDimension(R.styleable.TopBar_rightButtonTextSize, 0);    rightButtonBackground = ta.getDrawable(R.styleable.TopBar_rightButtonBackground);    // initial inner basic component    leftButton = new Button(context);    rightButton = new Button(context);    titleTextView = new TextView(context);    // 设置属性    titleTextView.setText(titleText);    titleTextView.setTextSize(titleTextSize);    titleTextView.setTextColor(titleTextColor);    titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);    titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);    titleTextView.setLayoutParams(titleLayoutParams);    leftButton.setText(leftButtonText);    leftButton.setTextSize(leftButtonTextSize);    leftButton.setBackground(leftButtonBackground);    leftBtnLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);    leftBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);    leftButton.setLayoutParams(leftBtnLayoutParams);    rightButton.setText(rightButtonText);    rightButton.setTextSize(rightButtonTextSize);    rightButton.setBackground(rightButtonBackground);    rightBtnLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);    rightBtnLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);    rightButton.setLayoutParams(rightBtnLayoutParams);    // 添加到View中    addView(titleTextView);    addView(leftButton);    addView(rightButton);    //addView(View child, ViewGroup.LayoutParams params);    ta.recycle();    leftButton.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        listener.onLeftButtonClicked();      }    });    rightButton.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {        listener.onRightButtonClicked();      }    });  }  /**   * 类的实例调用此方法   * 以匿名内部类的形式现实接口中的方法   * @param listener   */  public void setTopBarOnClickListener(TopBarOnClickListener listener){    this.listener = listener;  }  /**   * 设置导航背景颜色   * @param color   */  public void setTopBarBackgroundColor(int color){    this.setBackgroundColor(color);  }  /**   * 设置按钮是否可见   * @param show   */  public void setLeftButtonVisible(boolean show){    leftButton.setVisibility(show ? View.VISIBLE : View.GONE);  }  public void setRightButtonVisible(boolean show){    rightButton.setVisibility(show ? View.VISIBLE : View.GONE);  }}

 

需要带 Context context, AttributeSet attrs这两个参数的构造方法

别忘了addView() 将内部包含的控件添加到View中

 

在main.

<RelativeLayout ="http://schemas.android.com/apk/res/android"  ="http://schemas.android.com/tools"  ="http://schemas.android.com/apk/res-auto"  android:layout_width="match_parent"  android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">  <com.sphere.topbar.TopBar    android:id="@+id/topbar"    android:layout_width="match_parent"    android:layout_height="48dp"    myTopBar:titleText="自定义标题"    myTopBar:titleTextColor="#000"    myTopBar:titleTextSize="10sp"    myTopBar:leftButtonText="Back"    myTopBar:leftButtonBackground="#ff00ff"    myTopBar:leftButtonTextSize="10sp"    myTopBar:rightButtonText="More"    myTopBar:rightButtonBackground="#00ff00"    myTopBar:rightButtonTextSize="10sp"    /></RelativeLayout>

 

注意要添加名称空间,

如果是ADT开发环境,则需要这么写

注意虽然myTopBar名字可以随便起,但是不能使用android,否则会与系统冲突,ADT中引用时 需要在res后边接完整包名才可以。

引用自定义属性以(myTopBar:属性名)开头。

 

MainActivity.java

package com.sphere.topbar;import android.graphics.Color;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;public class MainActivity extends ActionBarActivity {  private TopBar mTopBar;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mTopBar = (TopBar)findViewById(R.id.topbar);    mTopBar.setBackgroundColor(Color.parseColor("#46B4CD"));    mTopBar.setTopBarOnClickListener(new TopBar.TopBarOnClickListener() {      @Override      public void onLeftButtonClicked() {        Toast.makeText(MainActivity.this,"Back",Toast.LENGTH_SHORT).show();      }      @Override      public void onRightButtonClicked() {        Toast.makeText(MainActivity.this, "More", Toast.LENGTH_SHORT).show();      }    });  }  @Override  public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.    getMenuInflater().inflate(R.menu.menu_main, menu);    return true;  }  @Override  public boolean onOptionsItemSelected(MenuItem item) {    int id = item.getItemId();    //noinspection SimplifiableIfStatement    if (id == R.id.action_settings) {      return true;    }    return super.onOptionsItemSelected(item);  }}

 

这里我们拿到自定义控件的实例,调用 setTopBarOnClickListener(TopBarOnClickListener listener)方法

为按钮添加点击事件监听器。

 

效果图如下: