Android学习——自定义控件(二)
生活随笔
收集整理的這篇文章主要介紹了
Android学习——自定义控件(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這篇文章來介紹自定義組合控件,自定義組合控件的應用場景很多,比如當你的UI如下時:
倘若不使用組合控件,則需要在XML文件中聲明4個TextView和4個EditText,而使用了組合控件,則只需要四個即可,方便很多。
自定義組合控件比自定義控件容易許多,因為其不涉及到相關的繪圖操作,只需要將已有的控件組合即可,接下來介紹其設計方法:
?
繪制Layout文件
自定義控件的Layout文件設計和ListView的Item類似,如上圖所示的設計,如下即可:
<?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="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="match_parent"android:id="@+id/describe_tv"android:gravity="bottom"android:paddingBottom="5dp"/><EditTextandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/describe_et"/></LinearLayout>?
聲明自定義屬性
這里的自定義屬性的聲明以及獲取均和自定義控件相同,如本例中,需要修改的便是TextView的文字以及文字的大小,那么屬性聲明文件以及屬性獲取代碼,如下即可:
<?xml version="1.0" encoding="utf-8"?> <resources><declare-styleable name="DescribeView"><attr name="text" format="string"/><attr name="textsize" format="dimension"/></declare-styleable> </resources>?
private void initattr(Context context, AttributeSet attrs){TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.DescribeView);String text=typedArray.getString(R.styleable.DescribeView_text);tv.setText(text);float size=typedArray.getDimension(R.styleable.DescribeView_textsize,30);tv.setTextSize(TypedValue.COMPLEX_UNIT_PX,size);}這里需要注意的是,tv.setTextSize默認設定的是dp值,而getDimension獲取的是px值,所以在setTextSize的時候,要設定size的類型為px,否則會出現字體過大的情況。
?
在Java文件中修改屬性值
想要在Java文件中修改屬性值,只需要設置相關的public函數即可,如
public void SetText(String s){tv.setText(s);}轉載于:https://www.cnblogs.com/J-inx/p/6622584.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Android学习——自定义控件(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: angularjs loading, a
- 下一篇: Oracle(21)—— Linux环境