Делаю макет айтема для ExpandableView, состоящий из двух TextView на одном уровне. При этом, хочу чтобы левый был прижат к левому краю макета, а правый - к правому. Правый всегда короткий, т.к. там только 5-7знаков, а левый может быть длинным, поэтому он с возможностью переноса.
Проблема у меня в том, что мне не удается все сделать красиво. Тексты либо наезжают друг на друга, либо не прижимаются к краям, либо вообще обрезаются О_о
И это при том, что на макете выглядит пристойно:
К сожалению. кода этой разметки не сохранил, вот текущая, после множественных экспериментов:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/diary_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="16dp"
android:gravity="start"
android:maxLines="3"
android:text="Title Logggg Title Looongeeeeeeeeeeeeee"
android:textAlignment="viewStart"
android:textColor="@color/colour_text"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/diary_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="16dp"
android:gravity="end"
android:text="@string/child_qty"
android:textAlignment="viewEnd"
android:textColor="@color/colour_text"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline2"
app:layout_constraintTop_toTopOf="parent" />
<android.support.constraint.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.8" />
</android.support.constraint.ConstraintLayout>
Перепробовал много чего, что казалось подходящим, и уже замучился. Посоветуйте грамотную разметку.
Подчеркну дополнительно - проблема вылезает именно в случае использования макета в качестве разметки айтема раскрывающегося списка (ExpandableListView). Как грамотно строить чилдрен ExpandableListView?
Код Активити и Адаптера вот такие:
TMPActivity.java:
package org.zav.food;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import org.zav.food.MyTypes.TextPare;
import org.zav.food.adapter.MyExpandableListAdapter;
import java.util.ArrayList;
import java.util.List;
public class TMPActivity extends AppCompatActivity {
private MyExpandableListAdapter mExpListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tmp_exp);
List<String> ExpandableList_group_List = new ArrayList<>(5);
ExpandableList_group_List.add("Завтрак");
ExpandableList_group_List.add("Обед");
ExpandableList_group_List.add("Полдник");
ExpandableList_group_List.add("Ужин");
ExpandableList_group_List.add("Хватит жрать!");
List<TextPare> ExpandableList_children_List = new ArrayList<>(5);
ExpandableList_children_List.add(new TextPare("Картошка", "100г"));
ExpandableList_children_List.add(new TextPare("Хрен", "100г"));
ExpandableList_children_List.add(new TextPare("масло", "100г"));
ExpandableList_children_List.add(new TextPare("Йад", "100г"));
final ExpandableListView ExpandableEatenToday = (ExpandableListView) findViewById(R.id.exp_list_0);
mExpListAdapter = new MyExpandableListAdapter(this);
ExpandableEatenToday.setAdapter(mExpListAdapter);
mExpListAdapter.Parents.addAll(ExpandableList_group_List);
// Пока заполняю хардкодово
// Надо будет заполнять данными из базы по кнопке Add
mExpListAdapter.Children1.addAll(ExpandableList_children_List);
mExpListAdapter.Children1.add(new TextPare("ХЗ", "0г"));
//обновляю отображение листа
mExpListAdapter.notifyDataSetChanged();
}
}
MyExpandableListAdapter.java:
package org.zav.food.adapter;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import org.zav.food.MyTypes.TextPare;
import org.zav.food.R;
import java.util.ArrayList;
import java.util.List;
public class MyExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
public List<String> Parents = new ArrayList<>();
//жестко задал 5 групп (приемов пищи).
//Каждая группа имеет свой список продуктов
public List<TextPare> Children0 = new ArrayList<>();
public List<TextPare> Children1 = new ArrayList<>();
public List<TextPare> Children2 = new ArrayList<>();
public List<TextPare> Children3 = new ArrayList<>();
public List<TextPare> Children4 = new ArrayList<>();
public MyExpandableListAdapter(Context context) {
this.mContext = context;
}
public Object getChild(int groupPosition, int childPosition)
{
switch (groupPosition){
case 0:
return Children0.get(childPosition);
case 1:
return Children1.get(childPosition);
case 2:
return Children2.get(childPosition);
case 3:
return Children3.get(childPosition);
case 4:
return Children4.get(childPosition);
default: return null;
}
}
public long getChildId(int groupPosition, int childPosition)
{
return childPosition;
}
public int getChildrenCount(int groupPosition)
{
// в зависимости от номера группы, смотрю размер листа соответствующей группы
switch (groupPosition){
case 0:
return Children0.size();
case 1:
return Children1.size();
case 2:
return Children2.size();
case 3:
return Children3.size();
case 4:
return Children4.size();
default:
return 0;
}
}
public TextView getGenericView()
{
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
TextView textView = new TextView(mContext);
textView.setLayoutParams(lp);
// Center the text vertically
textView.setGravity(Gravity.CENTER);
// Set the text starting position
textView.setPadding(55, 0, 0, 0);
return textView;
}
public Object getGroup(int groupPosition)
{
return Parents.get(groupPosition);
}
public int getGroupCount()
{
return Parents.size();
}
public long getGroupId(int groupPosition)
{
return groupPosition;
}
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return true;
}
public boolean hasStableIds()
{
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//convertView = inflater.inflate(R.layout.item_eaten_expandable_group, null);
convertView = inflater.inflate(R.layout.item_eaten_expandable_group, parent, false);
}
String group = Parents.get(groupPosition);
((TextView) convertView.findViewById(R.id.diary_group)).setText(group);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//convertView = inflater.inflate(R.layout.item_eaten_expandable_children, null);
convertView = inflater.inflate(R.layout.item_eaten_expandable_children, parent, false);
switch (groupPosition) {
case 0: {
((TextView) convertView.findViewById(R.id.diary_name)).setText(Children0.get(childPosition).getTxtFirst());
((TextView) convertView.findViewById(R.id.diary_qty)).setText(Children0.get(childPosition).getTxtSecond());
} break;
case 1: {
((TextView) convertView.findViewById(R.id.diary_name)).setText(Children1.get(childPosition).getTxtFirst());
((TextView) convertView.findViewById(R.id.diary_qty)).setText(Children1.get(childPosition).getTxtSecond());
} break;
case 2: {
((TextView) convertView.findViewById(R.id.diary_name)).setText(Children2.get(childPosition).getTxtFirst());
((TextView) convertView.findViewById(R.id.diary_qty)).setText(Children2.get(childPosition).getTxtSecond());
} break;
case 3: {
((TextView) convertView.findViewById(R.id.diary_name)).setText(Children3.get(childPosition).getTxtFirst());
((TextView) convertView.findViewById(R.id.diary_qty)).setText(Children3.get(childPosition).getTxtSecond());
} break;
case 4: {
((TextView) convertView.findViewById(R.id.diary_name)).setText(Children4.get(childPosition).getTxtFirst());
((TextView) convertView.findViewById(R.id.diary_qty)).setText(Children4.get(childPosition).getTxtSecond());
} break;
}
return convertView;
}
}
Класс TextPare:
package org.zav.food.MyTypes;
public class TextPare {
private String mTxtFirst;
private String mTxtSecond;
public TextPare() {
}
public TextPare(String txtFirst, String txtSecond) {
mTxtFirst = txtFirst;
mTxtSecond = txtSecond;
}
public String getTxtFirst() {
return mTxtFirst;
}
public void setTxtFirst(String txtFirst) {
mTxtFirst = txtFirst;
}
public String getTxtSecond() {
return mTxtSecond;
}
public void setTxtSecond(String txtSecond) {
mTxtSecond = txtSecond;
}
}