CheckedTextView Пользовательский макет для ListView - PullRequest
0 голосов
/ 21 апреля 2019

Я пытаюсь создать макет для строки ListView, которая содержит CheckedTextView с парой TextViews. Я обернул эти взгляды в RelativeLayout. При запуске приложения ничего не проверялось.

Я попытался найти решение, и оказалось, что если CheckedTextView не является представлением верхнего уровня макета, вам может потребоваться создать собственный макет, реализующий интерфейс Checkable. Я попытался следовать инструкциям здесь , но безуспешно. В моем случае TextViews, которые я пытаюсь установить, всегда имеют значение null в моем ArrayAdapter, поэтому я, очевидно, не делаю это правильно.

Есть идеи, что я делаю не так? У кого-нибудь есть пример, который соответствует моему сценарию, которому я мог бы следовать?

custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

<LinearLayout
    android:id="@+id/checkedTextViewLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_centerInParent="true"
    android:layout_margin="8dp">

    <CheckedTextView
        android:id="@+id/checkedTextView"
        android:layout_width="wrap_content"
        android:layout_height="?android:attr/listPreferredItemHeightSmall"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:gravity="center_vertical"
        android:checkMark="?android:attr/listChoiceIndicatorSingle"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" />

</LinearLayout>

<LinearLayout
    android:id="@+id/headingLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/checkedTextViewLayout"
    android:layout_alignParentStart="true"
    android:layout_margin="8dp"
    android:layout_toStartOf="@id/checkedTextViewLayout"
    android:orientation="vertical">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

CustomLayout.java

public class CustomLayout extends RelativeLayout implements Checkable {

public CustomLayout(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    initializeViews(context, attrs);
}

private void initializeViews(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.custom_layout, this);
    checkedTextView = this.findViewById(R.id.checkedTextView);
    heading = this.findViewById(R.id.heading);
    subheading = this.findViewById(R.id.subheading);
}...
}

list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<com.example.android.example.CustomLayout 
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/custom_layout_id">
</com.example.android.example.CustomLayout>

CustomArrayAdapter.java

if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.list_row, parent, false);
        viewHolder.customeLayout = convertView.findViewById(R.id.custom_layout_id);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    if (data != null) {
        viewHolder.customLayout.getHeading().setText("Order # " + data.getOrderNumber());
        viewHolder.customLayout.getSubheading().setText("Subheading");
    }

1 Ответ

0 голосов
/ 22 апреля 2019

Попробуйте это: -

custom_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?android:attr/selectableItemBackground"
android:padding="8dp">

<CheckedTextView
    android:id="@+id/checkedTextView"
    android:layout_width="wrap_content"
    android:layout_height="?android:attr/listPreferredItemHeightSmall"
    android:layout_alignParentEnd="true"
    android:layout_centerInParent="true"
    android:layout_margin="8dp"
    android:checkMark="?android:attr/listChoiceIndicatorSingle"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:textAppearance="?android:attr/textAppearanceListItemSmall" />

<LinearLayout
    android:id="@+id/headingLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_margin="8dp"
    android:layout_toStartOf="@id/checkedTextView"
    android:orientation="vertical">

    <TextView
        android:id="@+id/heading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>
</RelativeLayout>

CustomLayout.java: [Я получил идею по этой ссылке: Состояние Android LineableLayout, которое можно проверить на Android

public class CustomLayout extends RelativeLayout implements Checkable {

private CheckedTextView checkedTextView;
private TextView heading;
private TextView subheading;

public CustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
    setClickable(true);
    initializeViews(context, attrs);
}

private void initializeViews(Context context, AttributeSet attrs) {
    LayoutInflater.from(context).inflate(R.layout.custom_layout, this);
    checkedTextView = this.findViewById(R.id.checkedTextView);
    heading = this.findViewById(R.id.heading);
    subheading = this.findViewById(R.id.subheading);
}

public TextView getHeading() {
    return heading;
}

public TextView getSubheading() {
    return subheading;
}

@Override
public void setChecked(boolean b) {
    checkedTextView.setChecked(b);
}

@Override
public boolean isChecked() {
    return checkedTextView.isChecked();
}

@Override
public void toggle() {
    checkedTextView.setChecked(!checkedTextView.isChecked());
}

@Override
public boolean performClick() {
//        Toast.makeText(getContext(),"click",Toast.LENGTH_SHORT).show();
    toggle();
    return super.performClick();
}

}

Надеюсь, это поможет!

...