Android Resources + View + Layout

Resource

Elements or data that are “external” to the code, isolated from the business logic -- "Separation of Concern"

  • Stored in the res/ folder
  • Can be images, strings or XML files

What could be resources? Where to find them?

  • Layouts (res/layout)
  • UI controls -- eg. buttons (res/layout)
  • Images (res/drawable)
  • Strings (res/values/strings)
  • Style and theming information (res/values/styles)
  • Other -- eg. Color, dimensions, launcher icons (res/mipmap)

Alternative Resources

Alternative resources are used instead of the default resources in cirtain situations -- provide "localization"

  • Developer specify alternative resource folders
  • Android check the configuration of the device at runtime, and try to find an alternative resource that matches that config
  • If not found, use default

What could be alternative resources?

  • Language and region
  • Screen size
  • Screen orientation
  • Specifc screen pixel density
  • Platform version

XML syntax

  • Android specific attributes: namespaced with a android: prefix
  • Reference one resource from another: @[<package_name>:]<resource_type>/<resource_name>
  • Adding a new resource: android:id="@+id/identifier"

Resource (R) class

Upon compling, gradle creates an R class from the resource XML, it contains a giant list of static “constants” — one for each resource

These constants are organized into subclasses, one for each resource type

Each constant is actually an int, which serves as an index to that resource within the giant list.

Refering to a resource

[(package_name).]R.resource_type.identifier

eg. R.layout.activity_main, R.string.hello

Views

View is the superclass for visual interface elements, subclasses are TextViewsImageViewsButtons, etc. You can even build your won widgets!

If you are thinking of creating your own UI element:

  1. Create a class (for you UI element) that extends the View class
  2. Override default functions (eg. onTouchEvent)

View hierarchy

One subclass of View is ViewGroup, which can contain other “child” Views (including ViewGroup), this nested structure is called view hierarchy

View Methods

  1. GetText() -- String text = EditText.getText().toString();
  2. SetText() -- EditText.setText(text);

View Properties

All View have properties which define the state of the View. Properties are usually defined within the resource XML as element attributes

  • android:id: View identifier, unique within current layout
  • android:layout_widthandroid:layout_height: Defines height and width of the widget

    • Values: "match_parent" -- same as parent, "wrap_content" -- as big as its contents require

  • android:paddingandroid:paddingLeftandroid:marginandroid:marginLeft

    • Padding is the space between the content and the “edge” of the View, and margin is the space between Views

  • android: textSize, android:textColor

Setting properties

  1. Option 1: in XML
  2. Option 2: through Java methods (setText(), setPadding)

Menu Items

XML

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Settings" android:id="@+id/menu_settings"             
        android:icon="@android:drawable/ic_menu_preferences” />
    <item android:title="Help"
        android:id="@+id/menu_help"     
        android:icon="@android:drawable/ic_menu_info_details” />
    <item android:title="Exit"
        android:id="@+id/menu_exit"     
        android:icon="@android:drawable/ic_menu_close_clear_cancel" />
    <item android:title="Contacts" android:id="@+id/menu_contacts"     
        android:icon="@android:drawable/ic_menu_view" />
</menu>

In Parent View Class

  1. Set the options menu option to True
  2. Tell Activity to inflate the menu Layout
  3. Override other methods like onOptionsItemSelected and etc.
public View onCreateView(...) { 
    // . . . 
    setHasOptionsMenu(true);
}

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu, inflater); 
    inflater.inflate(R.menu.menu, menu);
}

Layouts

Collection of subclass of ViewGroup (subclass of View as well), used as a container of view elements (children)

TypeDescriptionAttributes
LinearLayout

All children arranged in a straight line

either vertically or horizontally

android:orientation -- Horizontal or Vetical

android:layout_weight -- blank spaces between children

RelativeLayout

All children are positioned “relative”

to the parent OR to each other

android:layout_verticalCenter: Put child in the

vertical center of the layout 

android:layout_toRightOf: Put child to the right of

the View with the given resource id

ConstraintLayout

Similar to RelativeLayout, but allows

adding constraints used to create highly

responsive layouts

See documentation

 

Using layouts

<include layout="@layout/sub_layout"> // To add layouts to another layout

Using the Layout Inflator:

LayoutInflator is a class that has the job of “inflating” (rendering) Views.

LayoutInflator inflator = getLayoutInflator(); //access the inflator (called on the Activity)
View myLayout = inflator.inflate(R.layout.my_layout, parentViewGroup, true); //to attach

Inflate() method arguments:

  1. Resource id of the layout to be inflated
  2. The ViewGroup where the layout to be inflated
  3. Whether the inflated view will be attached or not

ViewStub

A subclass of View that acts like an “on deck” Layout -- it is written into the XML, but isn’t actually shown (thus leaving a stube) until you call inflate() (or setVisible(View.VISIBLE)) on that stub.

In XML:

<ViewStub android:id="@+id/stub"
    android:inflatedId="@+id/subTree"
    android:layout="@layout/mySubTree"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

In Java:

ViewStub stub = (ViewStub)findViewById(R.id.stub);
View inflated = stub.inflate();

ViewModel

  • A androidx.lifecycle framework class.
  • A way of storing state for whatever gets shown to the user in a particular view, you CAN persist data and survive different life cycles!
  • Easy to perform unit tesing on ViewModel
  • Google suggests using activities and fragments to host data based on a view model combined with LiveData
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TypeArray 是 Android 中的一个特殊的资源类型,用于在 XML 中声明自定义 View 的属性。使用 TypeArray 可以方便地在 XML 布局中指定 View 的属性,而不需要在 Java 代码中进行硬编码。 使用 TypeArray 的步骤如下: 1. 在 res/values/attrs.xml 文件中定义自定义 View 的属性。 ```xml <resources> <declare-styleable name="MyCustomView"> <attr name="customAttr1" format="integer" /> <attr name="customAttr2" format="string" /> <attr name="customAttr3" format="boolean" /> </declare-styleable> </resources> ``` 2. 在自定义 View 的构造函数中获取 TypedArray 对象,并从中获取属性值。 ```java public class MyCustomView extends View { private int customAttr1; private String customAttr2; private boolean customAttr3; public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView); customAttr1 = a.getInt(R.styleable.MyCustomView_customAttr1, 0); customAttr2 = a.getString(R.styleable.MyCustomView_customAttr2); customAttr3 = a.getBoolean(R.styleable.MyCustomView_customAttr3, false); a.recycle(); } } ``` 在上面的代码中,`context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)` 用于获取 TypedArray 对象,`R.styleable.MyCustomView` 是在 attrs.xml 文件中定义的自定义属性集合,`a.getInt()`、`a.getString()`、`a.getBoolean()` 用于从 TypedArray 对象中获取属性值,最后需要调用 `a.recycle()` 来回收 TypedArray 对象。 3. 在 XML 布局中使用自定义 View,并设置属性值。 ```xml <com.example.MyCustomView android:layout_width="match_parent" android:layout_height="wrap_content" app:customAttr1="123" app:customAttr2="hello" app:customAttr3="true" /> ``` 在上面的代码中,`app:customAttr1`、`app:customAttr2`、`app:customAttr3` 是在 attrs.xml 文件中定义的自定义属性名,可以在 XML 布局中使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值