我尝试创建一个自定义的LinearLayout,它就像一个网格。我成功了,并且有了我想要的方面,但我仍然有问题。当我只有一行时。我想将自定义布局的layout_height属性从 wrap_content 更改为 march_parent ,以便能够将要创建的唯一LinearLayout居中。
所以现在我的代码是在 onFinishInflate 方法之后执行但我在这里遇到问题,我无法获得LayoutParams,因为值为null,当我尝试设置自己的新params,它不起作用:
setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
这是我的代码:
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class GameGridLayout extends LinearLayout {
private Context context;
private int currentRow = -1, maxRowItems = 3;
private ArrayList<LinearLayout> layouts = new ArrayList<>();
public GameGridLayout(Context context) {
super(context);
this.context = context;
}
public GameGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public GameGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
}
private ArrayList<View> getViews() {
int nbChilds = getChildCount();
ArrayList<View> views = new ArrayList<>();
for (int i = 0; i < nbChilds; i++) {
views.add(getChildAt(i));
}
return views;
}
private void reorganizeViews(Context context) {
ArrayList<View> views = getViews();
if(views.size() == 4) maxRowItems = 2;
for (int i = 0; i < views.size(); i++) {
if(i % maxRowItems == 0) {
LinearLayout currentLayout = new LinearLayout(context);
layouts.add(currentLayout);
currentRow++;
}
View currentChild = views.get(i);
if(currentChild != null) {
removeView(currentChild);
layouts.get(currentRow).addView(currentChild);
}
}
for (int i = 0; i < layouts.size(); i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
layouts.get(i).setLayoutParams(params);
layouts.get(i).setOrientation(HORIZONTAL);
layouts.get(i).setWeightSum(3);
layouts.get(i).setGravity(Gravity.CENTER);
addView(layouts.get(i));
}
setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
reorganizeViews(context);
}
}
如果你知道该怎么做,我看到如果我使用inflate方法,我可能会得到我想要的结果,但我不知道该怎么做,例如:
inflate(context, ??, this);
我没有任何xml来膨胀,所以......
答案 0 :(得分:0)
在setLayoutParams
中呼叫onFinishInflate
实际上无法正常工作,因为LayoutParams
的{{1}}将在以后添加到其父级时被覆盖。< / p>
我建议您在GameGridLayout
添加到其父级后调用setLayoutParams
。