I want to get the width of a LinearLayout element in my getView method of my custom adapter. My getView method looks like this:
@Override
public View getView(int position, View v, ViewGroup parent) {
View mView = v;
if (mView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mView = vi.inflate(R.layout.levelselector_item, null);
}
if (mView != null) {
...
LinearLayout ln = (LinearLayout) mView.findViewById(R.id.lineScore);
LinearLayout lnTotal = (LinearLayout) mView.findViewById(R.id.lineScoreTotal);
int widthTotal = lnTotal.getWidth()/2;
ln.getLayoutParams().height = 3;
ln.getLayoutParams().width = widthTotal;
ln.requestLayout();
ln.setBackgroundColor(Color.parseColor("#eef05e"));
}
return mView;
}
The problem my widthTotal doesn’t seem to have a value. If I click on an item of the gridview and hit the back button, then I suddenly see a yellow bar. If I enter ln.getLayoutParams().width = 20; he also shows a yellow short bar. I just don’t know when or where I can get the width of the LinearLayout…
I got it to work properly. For those who might be interested:
I first set my border around my gridview to an amount which is controlable by adding to my gridview in xml:
Then I used a combination of Ted Hopp’s and Sameer’s solution: Since I know what the padding of my elements is; 5dp around the gridview, 2dp between the elements and 15dp in an element. I also have 3 items each row, this makes my code look like:
And this takes me exactly where I want to be 🙂
Thanks!