Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 實例講解Android應用中自定義組合控件的方法

實例講解Android應用中自定義組合控件的方法

編輯:關於Android編程

自定義view大概可以分成:

  • 繼承view
  • 組合view
  • 自己畫的view(用paint和canvas)
  • 自定義viewgroup(widget)

最近又跟同學聊起來了,於是就准備自己實現一個imagebutton來練練手。(最簡單的了)以及後面一個把imageview與textview結合使用的案例。

ImageButton
要實現ImageButton最容易想到的不就是把button和imageview合在一起麼。嗯,人容易就想到這是一個組合自定義view。可是如何把一個image放到button上呢,自然就是用一個FrameLayout把button和imageview包裹起來,然後將這個layout當作一個weidgt。把一個layout當成一個控件我開始不太理解。後來了解到一些東西。

補充知識點(安卓的頂層視圖)
在android裡面,你的app界面的活動的視圖並非是最頂級的視圖。大家應該都知道viewtree。在安卓裡面,最頂級的視圖是一個叫DecorView的東西。它包括你的狀態欄,標題欄,以及你的活動界面。而且這個活動界面,安卓會自動幫你提前弄進去一個FrameLayout。可以這麼理解吧,在安卓這個上帝的面前,你的activity就是放在他的framelayout的一個個view。上一張圖~

2016415144141959.png (476×449)

DecorView->LinearLayout(狀態欄和activity)->FrameLayout(activity)->你自己的acitivty視圖。

實例講解
好啦,回歸正題。我上代碼了。
myimagebutton_layout.xml

<FrameLayout  
 xmlns:android="http://schemas.android.com/apk/res/android"    
 android:layout_width="match_parent"       
 android:layout_height="match_parent">  
 <Button    
  android:layout_width="match_parent"    
  android:layout_height="match_parent"    
  android:id="@+id/button_imagebutton"    />  
 <ImageView 
  android:layout_width="match_parent"    
  android:layout_height="match_parent"    
  android:id="@+id/imageview_button"    />
</FrameLayout>

用一個framelayout把兩個控件裝起來,然後組合。組合了之後我們就去自定義我們這個控件的屬性。button不用變對吧,用原生的就好了,就是需要有一個圖片的src這個屬性就好了。
在values目錄下的attrs.xml文件_

<?xml version="1.0" encoding="utf-8"?>
<resources>在
  <declare-styleable name="MyImageButton">
    <attr name="Imagesrc" format="reference"/>
  </declare-styleable>
</resources>

一般來說,declare-styleable標簽的名字都是你的自定義控件的名字。attr就是你的自定義控件屬性。format是這個屬性的值的數據類型。這裡的reference表示引用。dimension表示的是dp或者sp的大小。還有一些可以自己去看看。定義好屬性,我們就開始寫控件了。
MyImageButton.java

public class MyImageButton2 extends FrameLayout{

  ImageView mImageView;
  Button mButton;
  int resId;

  public MyImageButton2(Context context) {
    super(context);
  }

  public MyImageButton2(Context context, AttributeSet attrs) {
    super(context, attrs);
    //導入布局
    LayoutInflater.from(context).inflate(R.layout.myimagebutton_layout, this);

   mImageView=(ImageView)findViewById(R.id.imageview_button);

   mButton = (Button) findViewById(R.id.button_imagebutton);
    //獲得這個控件對應的屬性。
   TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyImageButton);

    try{
     //獲得屬性值
      resId = a.getResourceId(R.styleable.MyImageButton_Imagesrc, 0);
    }finally {
     //回收這個對象
      a.recycle();
    }

    if(resId != 0){
      mImageView.setImageResource(resId);
    }
  }

  public void setImage(int resId){
    mImageView.setImageResource(resId);
  }

}

一般來說,繼承view(就這麼說吧,反正都是都是繼承view的),實現兩三個構造函數就可以了。在第二個裡面有一個attr,這就是傳進來的屬性。如果resId不為默認值,就表示用戶在xml裡面傳入了這個屬性值,你也必須要寫一個set方法,讓用戶可以在java代碼中去改變屬性值。
test.myimagebutton.layout.xml_

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.example.think.testview.customview.MyImageButton2
    xmlns:pt = "http://schemas.android.com/apk/res/com.example.think.testview"
    android:layout_height="100dp"
    android:layout_width="match_parent"
    pt:Imagesrc = "@drawable/ic_launcher"
    />

</LinearLayout>

效果圖

2016415144239601.png (1080×1920)

另一個實例

這裡我們來看一個view組合控件的例子:

2016415144305792.jpg (1187×294)

<string-array name="bao_type"> 
   <item>測試1</item> 
   <item>測試2</item> 
   <item>測試3</item> 
   <item>測試4</item> 
 </string-array> 

<?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:background="@color/gray_common_background" 
  android:orientation="vertical"> 
 
 
 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
 
    <TextView 
      android:id="@+id/txt_viewpage_bar1" 
       
      android:textColor="@color/theme_red" /> 
 
    <TextView 
      android:id="@+id/txt_viewpage_bar2" 
       /> 
 
    <TextView 
      android:id="@+id/txt_viewpage_bar3" 
       /> 
 
    <TextView 
      android:id="@+id/txt_viewpage_bar4" 
       /> 
  </LinearLayout> 
 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
 
    <View 
      android:id="@+id/view_viewpage_bar1" 
       /> 
 
    <View 
      android:id="@+id/view_viewpage_bar2" 
       /> 
 
    <View 
      android:id="@+id/view_viewpage_bar3" 
       /> 
 
    <View 
      android:id="@+id/view_viewpage_bar4" 
       /> 
  </LinearLayout> 
 
 
 
  <android.support.v4.view.ViewPager 
    android:id="@+id/common_viewpage_buttom" 
    android:layout_width="match_parent" 
    android:layout_height="0dp" 
    android:layout_weight="1" /> 
</LinearLayout> 

public interface SlbPageViewOnPageChangeListener { 
   void onPageSelected(int position); 
 
   void onPageScrollStateChanged(int state); 
 } 

public class SlbPageViewBar extends LinearLayout { 

  private TextView[] mTotalTxtViews; 
  private View[] mTotalViews; 
  private List<TextView> mTxtViews; 
  private List<View> mViews; 
 
  private ViewPager mViewPager; 
  private SlbPageViewOnPageChangeListener mSlbPageViewOnPageChangeListener; 
 
 
  public SlbPageViewBar(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    mTotalTxtViews = new TextView[4]; 
    mTotalViews = new View[4]; 
    mTxtViews = new ArrayList<>(); 
    mViews = new ArrayList<>(); 
    initView(); 
  } 
 
  private void initView() { 
    View.inflate(getContext(), R.layout.layout_common_top_pageview_bar, this); 
    mViewPager = (ViewPager) findViewById(R.id.common_viewpage_buttom); 
    mTotalTxtViews[0] = (TextView) findViewById(R.id.txt_viewpage_bar1); 
    mTotalTxtViews[1] = (TextView) findViewById(R.id.txt_viewpage_bar2); 
    mTotalTxtViews[2] = (TextView) findViewById(R.id.txt_viewpage_bar3); 
    mTotalTxtViews[3] = (TextView) findViewById(R.id.txt_viewpage_bar4); 
    mTotalViews[0] = findViewById(R.id.view_viewpage_bar1); 
    mTotalViews[1] = findViewById(R.id.view_viewpage_bar2); 
    mTotalViews[2] = findViewById(R.id.view_viewpage_bar3); 
    mTotalViews[3] = findViewById(R.id.view_viewpage_bar4); 
 
  } 
 
  /** 
   * @param title 標題名稱數組 
   */ 
 
  public void setTitleView(String[] title) { 
    int legth = title.length > 4 ? 4 : title.length; 
    for (int i = 0; i < legth; i++) { 
      mTotalTxtViews[i].setText(title[i]); 
      mTotalTxtViews[i].setVisibility(View.VISIBLE); 
      mTotalViews[i].setVisibility(View.INVISIBLE); 
      mTotalTxtViews[i].setOnClickListener(new SlbTextViewOnLister(i)); 
      mTxtViews.add(mTotalTxtViews[i]); 
      mViews.add(mTotalViews[i]); 
    } 
    mTotalViews[0].setVisibility(View.VISIBLE); 
    mViewPager.setOnPageChangeListener(mOnButtomPageChangeListener); 
  } 
 
  public ViewPager getViewPager(){ 
    return mViewPager; 
  } 
 
  public void setSlbPageViewOnPageChangeListener(SlbPageViewOnPageChangeListener slbPageViewOnPageChangeListener) { 
    this.mSlbPageViewOnPageChangeListener = slbPageViewOnPageChangeListener; 
  } 
 
  private void changeViewBg(int textViewId, int viewId) { 
    for (View view : mViews) { 
      if (viewId == view.getId()) { 
        view.setVisibility(View.VISIBLE); 
      } else { 
        view.setVisibility(View.INVISIBLE); 
      } 
    } 
    for (TextView view : mTxtViews) { 
      if (textViewId == view.getId()) { 
        view.setTextColor(getResources().getColor(R.color.theme_red)); 
      } else { 
        view.setTextColor(getResources().getColor(R.color.black_normal_text_33333)); 
      } 
    } 
  } 
 
 
  class SlbTextViewOnLister implements OnClickListener { 
 
    private int mItem; 
 
 
    public SlbTextViewOnLister(int item) { 
      this.mItem = item; 
 
    } 
 
    @Override 
    public void onClick(View v) { 
      mViewPager.setCurrentItem(mItem); 
    } 
  } 
 
  private ViewPager.OnPageChangeListener mOnButtomPageChangeListener = new ViewPager.OnPageChangeListener() { 
    @Override 
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 
 
    } 
 
    @Override 
    public void onPageSelected(int position) { 
      switch (position) { 
        case 0: 
          changeViewBg(R.id.txt_viewpage_bar1, R.id.view_viewpage_bar1); 
          break; 
        case 1: 
          changeViewBg(R.id.txt_viewpage_bar2, R.id.view_viewpage_bar2); 
 
          break; 
        case 2: 
          changeViewBg(R.id.txt_viewpage_bar3, R.id.view_viewpage_bar3); 
          break; 
        case 3: 
          changeViewBg(R.id.txt_viewpage_bar4, R.id.view_viewpage_bar4); 
          break; 
      } 
      if (mSlbPageViewOnPageChangeListener != null) 
        mSlbPageViewOnPageChangeListener.onPageSelected(position); 
    } 
 
    @Override 
    public void onPageScrollStateChanged(int state) { 
      if (mSlbPageViewOnPageChangeListener != null) 
        mSlbPageViewOnPageChangeListener.onPageScrollStateChanged(state); 
    } 
  }; 
 
 
} 

public class CommonViewpageAdapter extends FragmentPagerAdapter { 
  private List<Fragment> mFragments; 
  private String [] mTitles; 
 
  public CommonViewpageAdapter(FragmentManager fm, List<Fragment> fragments, String [] titles) { 
    super(fm); 
    mFragments = fragments; 
    mTitles = titles; 
  } 
 
  @Override 
  public Fragment getItem(int position) { 
    return mFragments.get(position); 
  } 
 
  @Override 
  public int getCount() { 
    return mFragments.size(); 
  } 
 
  @Override 
  public CharSequence getPageTitle(int position) { 
    return mTitles[position]; 
  } 
 
  @Override 
  public void destroyItem(ViewGroup container, int position, Object object) { 
    super.destroyItem(container, position, object); 
  } 
} 

<com.slfinance.app.slb.common.ui.view.SlbPageViewBar 
    android:id="@+id/slbpv_buy_huoqibao_SlbPageViewBarshow" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"/> 

private void initButtomPageFragment(SlbPageViewBar slbPageViewBar) { 
  List<Fragment> fragmentList = new ArrayList<>(); 
  Test1Fragment test1Fragment = new Test1Fragment(); 
  Test2Fragment test2Fragment = new Test2Fragment(); 
  Test3Fragment test3Fragment = new Test3Fragment(); 
  Test4Fragment test4Fragment = new Test4Fragment(); 
  fragmentList.add(test1Fragment); 
  fragmentList.add(test2Fragment); 
  fragmentList.add(test3Fragment); 
  fragmentList.add(test4Fragment); 
  String[] titles = getResources().getStringArray(R.array.buy_huoqi_bao_zanquan_detail); 
  slbPageViewBar.setTitleView(titles); 
  CommonViewpageAdapter viewPagerAdapter = new CommonViewpageAdapter( 
      getSupportFragmentManager(), fragmentList, titles); 
  mButtomPageView.setAdapter(viewPagerAdapter); 
  mButtomPageView.setOffscreenPageLimit(3); 
  mButtomPageView.setCurrentItem(0); 
} 


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved