У меня есть Gridview, что я не хочу постоянной высоты строки. Я хочу, чтобы высота строки изменялась для размещения самого высокого содержания в каждой строке. В настоящее время я использую https://stackoverflow.com/a/7568226/1149456 (измененный, поэтому я могу возобновить работу с несколькими адаптерами) в качестве своего решения, но у меня возникла проблема. Строки все правильны правильно, пока я не открою второй фрагмент.Android Gridview Row Height Issue
Например, я открываю список достижений категорий фрагмента фрагмент 1 и когда вы выбираете категорию новый фрагмент открыт со списком подкатегорий в фрагменте 2. Первый элемент не изменяется, если второй больше, например, здесь, в этом screenshot.
Если я открываю фрагмент 2, сначала он правильно изменяет размеры, или если я прокручиваю вверх и вниз, он правильно изменяется таким образом, как это screenshot.
AutoMeasureGridView.java
public class AutoMeasureGridView extends GridView {
private ListAdapter mAdapter;
public AutoMeasureGridView(Context context) {
super(context);
}
public AutoMeasureGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoMeasureGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(ListAdapter adapter) {
this.mAdapter = adapter;
super.setAdapter(adapter);
super.setAdapter(this.mAdapter);
}
@Override
public ListAdapter getAdapter() {
return this.mAdapter;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if(changed) {
//TutorialAdapter adapter = (TutorialAdapter)getAdapter();
int numColumns = getNumColumns();
if(getAdapter() != null) {
GridViewItemLayout.initItemLayout(numColumns, getAdapter().getCount());
}
/*if(numColumns > 1) {
int columnWidth = getMeasuredWidth()/numColumns;
adapter.measureItems(columnWidth);
}*/
}
super.onLayout(changed, l, t, r, b);
}
}
Исходный код вызывает adapter.measureItems (ColumnWidth);, но я нашел код для большей части без него, и я не смог бы повторно использовать код с несколькими адаптерами, вызвав пользовательскую функцию.
GridViewItemLayout.java общественного класса GridViewItemLayout расширяет LinearLayout {
// Array of max cell heights for each row
private static int[] mMaxRowHeight;
// The number of columns in the grid view
private static int mNumColumns;
// The position of the view cell
private int mPosition;
// Public constructor
public GridViewItemLayout(Context context) {
super(context);
}
// Public constructor
public GridViewItemLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Set the position of the view cell
* @param position
*/
public void setPosition(int position) {
mPosition = position;
}
/**
* Set the number of columns and item count in order to accurately store the
* max height for each row. This must be called whenever there is a change to the layout
* or content data.
*
* @param numColumns
* @param itemCount
*/
public static void initItemLayout(int numColumns, int itemCount) {
mNumColumns = numColumns;
mMaxRowHeight = new int[itemCount];
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Do not calculate max height if column count is only one
if(mNumColumns <= 1 || mMaxRowHeight == null) {
return;
}
// Get the current view cell index for the grid row
int rowIndex = mPosition/mNumColumns;
// Get the measured height for this layout
int measuredHeight = getMeasuredHeight();
// If the current height is larger than previous measurements, update the array
if(measuredHeight > mMaxRowHeight[rowIndex]) {
mMaxRowHeight[rowIndex] = measuredHeight;
}
// Update the dimensions of the layout to reflect the max height
setMeasuredDimension(getMeasuredWidth(), mMaxRowHeight[rowIndex]);
}
}
Я пытался как achievementAdapter.notifyDataSetChanged(); и достижениеListView.invalidateViews(); но не заставили его изменить размер.
AchievementAdapter.java общественного класса AchievementAdapter расширяет ArrayAdapter {
private final Context context;
private final ArrayList<AchievementsItem> swtorAchievements;
int AdvancedPos1;
int AdvancedPos2;
String type;
public AchievementAdapter(Context context, ArrayList<AchievementsItem> swtorAchievements, String type) {
super(context, R.layout.achievement_row, swtorAchievements);
this.context = context;
this.swtorAchievements = swtorAchievements;
this.type = type;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = null;
final AchievementsItem item = swtorAchievements.get(position);
if(item.isGroupHeader()){
rowView = inflater.inflate(R.layout.advanced_class_tab3_header, parent, false);
TextView txtHeader = (TextView) rowView.findViewById(R.id.txtAbilityTitle);
txtHeader.setText(item.getTitle());
} else {
rowView = inflater.inflate(R.layout.achievement_row, parent, false);
TextView txtViewCategory1 = (TextView) rowView.findViewById(R.id.txtCategory1);
TextProgressBar txtViewProgress = (TextProgressBar) rowView.findViewById(R.id.progressBarWithText);
if (item != null) {
if (type.equals("")) {
txtViewCategory1.setText(item.getCategory1());
} else if (type.equals("category1")) {
txtViewCategory1.setText(item.getCategory1());
} else if (type.equals("category2")) {
txtViewCategory1.setText(item.getCategory2());
} else if (type.equals("category3")) {
txtViewCategory1.setText(item.getCategory3());
}
txtViewProgress.setText("0/" + item.getCount());
}
}
return rowView;
}
}