Пользовательские компоненты


Реализация собственных компонентов в предварительно встроенных компонентах с расширением подкласса с собственным определенным классом

Способ оплаты, который выберете вы!
Android предлагает большой список предварительно созданных виджетов, таких как Button, TextView, EditText, ListView, CheckBox, RadioButton, Gallery, Spinner, AutoCompleteTextView и т. Д., Которые можно использовать непосредственно при разработке приложений Android, но может возникнуть ситуация, когда вы не удовлетворены существующей функциональностью любого из доступных виджетов. Android предоставляет вам средства для создания собственных пользовательских компонентов, которые вы можете настроить в соответствии со своими потребностями.

Если вам нужно всего лишь внести небольшие изменения в существующий виджет или макет, вы можете просто создать подкласс виджета или макета и переопределить его методы, что даст вам точный контроль над внешним видом и функциями элемента экрана.

В этом руководстве объясняется, как создавать собственные представления и использовать их в своем приложении с помощью простых и простых шагов.

изготовленный на заказ
Пример пользовательских компонентов в иерархии пользовательских представлений
Создание простого пользовательского компонента
шаг Описание
1 Вы будете использовать IDE Android studio для создания приложения Android и назовите его myapplication в пакете com.example.tutorialspoint7.myapplication, как описано в главе « Пример Hello World» .
2 Создайте XML-файл res / values ​​/ attrs.xml, чтобы определить новые атрибуты вместе с их типом данных.
3 Создайте файл src / mainactivity.java и добавьте код для определения вашего пользовательского компонента.
4 Измените файл res / layout / activity_main.xml и добавьте код для создания экземпляра составного представления Color вместе с несколькими атрибутами по умолчанию и новыми атрибутами.
5 Запустите приложение, чтобы запустить эмулятор Android, и проверьте результат изменений, внесенных в приложение.
Создайте следующий файл атрибутов с именем attrs.xml в папке res / values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TimeView">
<declare-styleable name="TimeView">
<attr name="title" format="string" />
<attr name="setColor" format="boolean"/>
</declare-styleable>
</declare-styleable>
</resources>
Измените файл макета, используемый действием, следующим образом.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<com.example.tutorialspoint7.myapplication.TimeView
android:id="@+id/timeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:title="my time view"
custom:setColor="true" />

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/simple"
android:layout_below="@id/timeView"
android:layout_marginTop="10dp" />
</RelativeLayout>
Создайте следующий Java-файл с именем timeview для вашего составного представления.

package com.example.tutorialspoint7.myapplication;
/**
* Created by TutorialsPoint7 on 9/14/2016.
*/
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.res.TypedArray;

import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimeView extends TextView {
private String titleText;
private boolean color;

public TimeView(Context context) {
super(context);
setTimeView();
}

public TimeView(Context context, AttributeSet attrs) {
super(context, attrs);
// retrieved values correspond to the positions of the attributes
TypedArray typedArray = context.obtainStyledAttributes(attrs,
R.styleable.TimeView);
int count = typedArray.getIndexCount();
try{

for (int i = 0; i < count; ++i) {

int attr = typedArray.getIndex(i);
// the attr corresponds to the title attribute
if(attr == R.styleable.TimeView_title) {

// set the text from the layout
titleText = typedArray.getString(attr);
setTimeView();
} else if(attr == R.styleable.TimeView_setColor) {
// set the color of the attr "setColor"
color = typedArray.getBoolean(attr, false);
decorateText();
}
}
}

// the recycle() will be executed obligatorily
finally {
// for reuse
typedArray.recycle();
}
}

public TimeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setTimeView();
}

private void setTimeView() {
// has the format hour.minuits am/pm
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String time = dateFormat.format(Calendar.getInstance().getTime());

if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}

private void decorateText() {
// when we set setColor attribute to true in the XML layout
if(this.color == true){
// set the characteristics and the color of the shadow
setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));
setBackgroundColor(Color.CYAN);
} else {
setBackgroundColor(Color.RED);
}
}
}
Измените свой Java-файл Основной активности на следующий код и запустите приложение.

package com.example.tutorialspoint7.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView simpleText = (TextView) findViewById(R.id.simple);
simpleText.setText("That is a simple TextView");
}
}
Запущенное приложение должно выглядеть следующим образом.