I am absolutely bigenner in android programming. I have done so far like this..
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.scorecard_fragment, container,
false);
gridLayout = (GridLayout) view.findViewById(R.id.GridLayout1);
/*** Default first row */
gridLayout.setColumnCount(col);
gridLayout.setRowCount(row);
if (col == 1) {
defaultColumn();
}
else {
extendedColumn("");
}
return view;
}
public void defaultColumn() {
// Log.d(TAG, "Default col");
int i;
int k = 1;
for (i = 0; i < 20; i++) {
if (i == 0)
{
ImageView oImageView = new ImageView(getActivity());
oImageView.setImageResource(R.drawable.ic_player);
GridLayout.LayoutParams param = new
GridLayout.LayoutParams();
param.setMargins(0, 0, 0, 0);
gridLayout.addView(oImageView);
} else if (i < 19) {
TextView oTextView = new TextView(getActivity());
oTextView.append("" + (k++) + "\n");
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.setGravity(Gravity.CENTER);
param.setMargins(15, 15, 15, 15);
oTextView.setLayoutParams(param);
gridLayout.addView(oTextView);
} else {
TextView oTextView = new TextView(getActivity());
oTextView.append("\n");
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.setGravity(Gravity.CENTER);
param.setMargins(15, 15, 15, 15);
oTextView.setLayoutParams(param);
gridLayout.addView(oTextView);
}
}
col++;
}
public void extendedColumn(String str) {
Log.d("", "value c1" + col);
int i;
for (i = 0; i < 20; i++) {
if (i == 0)
{
TextView oTextView = new TextView(getActivity());
oTextView.setText(str);
gridLayout.addView(oTextView);
// oTextView.setBackgroundResource(R.drawable.border);
oTextView.setTextSize(14);
}
else if (i < 19) {
Log.d("Implement spinner", "sdfsdfsdf");
final Spinner s1 = new Spinner(getActivity());
final ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(getActivity(), R.array.score_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
updateResult();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
gridLayout.addView(s1);
}
else {
TextView oTextView = new TextView(getActivity());
oTextView.append("\n");
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.setGravity(Gravity.CENTER);
param.setMargins(15, 15, 15, 15);
oTextView.setLayoutParams(param);
gridLayout.addView(oTextView);
}
}
col++;
}
public void updateResult() {
int j = gridLayout.getColumnCount();
Log.d(" Column count", "" + j);
int k = gridLayout.getRowCount();
Log.d(" Row count", "" + k);
}
As you can see I am trying get the value from spinner and its current row and column value. I can do that using gridLayout.getColumnCount() and gridLayout.getRowCount(). But that gives me always the total column and row depend on how many user I have. But I want to get the specific row and column no matter how many user I have so that I can calculate my result by knowing which row and column has been selected by which user..Helps or suggestion will be highly appreciated.
so that I can calculate my result by knowing which value has been selected
To only know the selected value, just implement the onItemClick() method, and inside you will have position of selected value, the view, the parent ViewGroup, etc ...
Related
I have created a textview dynamically in android. When i clicked the textview the color changes from white to orange, but what i want is when i clicked another textview, the other textview that has been changed to orange will change back to white.
This is the code to create the textview:
for (int i = 1; i <= n; i++) {
final TextView mPageNumber = new TextView(getActivity());
mPageNumber.setText("" + i);
mPageNumber.setId(Integer.parseInt(String.valueOf(i)));
mPageNumber.setTextColor(getResources().getColor(R.color.colorWhite));
mPageNumber.setPadding(60,30,60,30);
final int id_ = mPageNumber.getId();
LinearLayout layout = (LinearLayout) getView().findViewById(R.id.pagination);
layout.setBackgroundResource(R.color.colorPrimary);
layout.addView(mPageNumber);
OnClickListener
mPageNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toastMessage!= null) {
toastMessage.cancel();
}
toastMessage = Toast.makeText(getActivity().getApplicationContext(), "Button with id =" + id_ +
" is clicked",Toast.LENGTH_SHORT);
current = id_;
toastMessage.show(); mPageNumber.setTextColor(getResources().getColor(R.color.colorOrange));
You can iterate through all the child in the layout and set the color as white and then the selected color as orange like this in below example.
LinearLayout layout;
private void setAllTextColorAsWhite() {
if(layout == null) {
return;
}
int childCount = layout.getChildCount();
for (int i = 0; i < childCount; i++) {
TextView textView = (TextView) layout.getChildAt(i);
textView.setTextColor(getResources().getColor(R.color.white));
}
}
public void setTextViews() {
layout = (LinearLayout) getView().findViewById(R.id.pagination);
layout.removeAllViews();
for (int i = 1; i <= n; i++) {
final TextView mPageNumber = new TextView(getActivity());
mPageNumber.setText("" + i);
mPageNumber.setId(Integer.parseInt(String.valueOf(i)));
mPageNumber.setTextColor(getResources().getColor(R.color.colorWhite));
mPageNumber.setPadding(60, 30, 60, 30);
final int id_ = mPageNumber.getId();
layout.setBackgroundResource(R.color.colorPrimary);
layout.addView(mPageNumber);
mPageNumber.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toastMessage!= null) {
toastMessage.cancel();
}
toastMessage = Toast.makeText(getActivity().getApplicationContext(), "Button with id =" + id_ +
" is clicked",Toast.LENGTH_SHORT);
current = id_;
toastMessage.show();
setAllTextColorAsWhite();
mPageNumber.setTextColor(getResources().getColor(R.color.colorOrange));
}
});
}
}
You can using like this :~
mPageNumber.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
textView.setTextColor(Color.RED);
break;
case MotionEvent.ACTION_UP:
textView.setTextColor(Color.BLUE);
break;
}
return false;
}
});
you have to do like this
for (int i = 1; i <= n; i++) {
final TextView mPageNumber = new TextView(getActivity());
mPageNumber.setText("" + i);
mPageNumber.setId(Integer.parseInt(String.valueOf(i)));
mPageNumber.setTextColor(getResources().getColor(R.color.colorWhite));
mPageNumber.setPadding(60,30,60,30);
mPageNumber.setOnClickListener(this);
final int id_ = mPageNumber.getId();
LinearLayout layout = (LinearLayout) getView().findViewById(R.id.pagination);
layout.setBackgroundResource(R.color.colorPrimary);
layout.addView(mPageNumber);
now you have to implement onclick method like this
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.1:
//code for click textview.
break;
}
}
happy coding.
The easiest way is to save the TextView reference to an array, like this:
final TextView[] mPageNumbers;
for (int i = 1; i <= n; i++) {
mPageNumbers[i] = new TextView(getActivity());
mPageNumber[i].setText("" + i);
.
.
.
for (int i=0; i<mPageNumbers.length; i++) {
if (view.getId() == mPageNumbers[i].getId()) {
mPageNumber.setTextColor(getResources().getColor(R.color.colorOrange));
} else {
mPageNumber.setTextColor(getResources().getColor(R.color.colorWhite));
}
}
And in the end, you loop the TextView references, and then set the color manually, if the id is same, set orange, if different (means other textViews), set white.
I have a list view where every item is a MPAndroidChart. The problem is that on the chart i set some gestures but when i try to perform these the list view intercept the gesture and perform the scroll.
Now i want to maintain the scroll of the list view but i want to perform the gesture on chart, how this is possible?
Also disable the scroll is useless because the list view anyway intercept the touch event and sto to perform the gesture on chart.
So what i want to do is to stop the list view to intercept the chart gesture but maintain the scroll of the list view
Class of the list view
public class ListViewMultiChartActivity extends DemoBase {
public static Button check_button, close_button;
public static LineChartItem chart;
public static ScatterChartItem chart2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_listview_chart);
check_button = (Button) findViewById(R.id.button);
close_button = (Button) findViewById(R.id.button2);
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayList<ChartItem> list = new ArrayList<ChartItem>();
list.add(new LineChartItem(generateDataLine(0), getApplicationContext()));
list.add(new ScatterChartItem(generateDataScatter(1), getApplicationContext()));
ChartDataAdapter cda = new ChartDataAdapter(getApplicationContext(), list);
lv.setAdapter(cda);
chart = (LineChartItem) list.get(0);
chart2 = (ScatterChartItem) list.get(1);
check_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chart.mChart.end_selection || chart2.mChart.end_selection) {
Highlight[] high;
if (chart.mChart.end_selection) {
high = chart.mChart.getHighlighted();
} else {
high = chart2.mChart.getHighlighted();
}
ArrayList<Entry> position;
ArrayList<Entry> position2;
LineDataSet d;
ScatterDataSet d2;
int i;
int j = 0;
int size = chart.mChart.getData().getDataSetCount();
while (j < size) {
i = 0;
position = new ArrayList<>();
position2 = new ArrayList<>();
while (i < high.length) {
int k = 0;
while (k < chart.mChart.getData().getDataSetByIndex(j).getEntryCount()) {
if (high[i].getX() == chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k).getX() && j == high[i].getDataSetIndex()) {
position.add(chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k));
position2.add(chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k));
}
k++;
}
i++;
}
if (position.size() != 0) {
d = new LineDataSet(position, "Data" + j);
d.setLineWidth(2.5f);
d.setCircleRadius(4f);
int color = mColors[j % mColors.length];
d.setColor(color);
d.setCircleColor(color);
chart.mChart.getData().addDataSet(d);
d2 = new ScatterDataSet(position2, "Data" + j);
d2.setColor(color);
chart2.mChart.getData().addDataSet(d2);
}
j++;
}
i = 0;
while (i < size) {
chart.mChart.getData().removeDataSet(0);
chart2.mChart.getData().removeDataSet(0);
i++;
}
Highlight[] highvoid = new Highlight[0];
chart.mChart.highlightValues(highvoid);
chart2.mChart.highlightValues(highvoid);
chart.mChart.invalidate();
chart2.mChart.invalidate();
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
}
}
});
close_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (chart.mChart.end_selection || chart2.mChart.end_selection) {
Highlight[] high;
if (chart.mChart.end_selection) {
high = chart.mChart.getHighlighted();
} else {
high = chart2.mChart.getHighlighted();
}
int i = 0;
int j = 0;
while (i < high.length) {
j = 0;
while (j < chart.mChart.getData().getDataSetCount()) {
int k = 0;
while (k < chart.mChart.getData().getDataSetByIndex(j).getEntryCount()) {
if (high[i].getX() == chart.mChart.getData().getDataSetByIndex(j).getEntryForIndex(k).getX() && j == high[i].getDataSetIndex()) {
chart.mChart.getData().getDataSetByIndex(j).removeEntry(k);
chart2.mChart.getData().getDataSetByIndex(j).removeEntry(k);
}
k++;
}
j++;
}
i++;
}
Highlight[] highvoid = new Highlight[0];
chart.mChart.highlightValues(highvoid);
chart2.mChart.highlightValues(highvoid);
chart.mChart.invalidate();
chart2.mChart.invalidate();
check_button.setVisibility(View.INVISIBLE);
close_button.setVisibility(View.INVISIBLE);
}
}
});
}
/**
* adapter that supports 3 different item types
*/
private class ChartDataAdapter extends ArrayAdapter<ChartItem> {
public ChartDataAdapter(Context context, List<ChartItem> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getItem(position).getView(position, convertView, getContext());
}
#Override
public int getItemViewType(int position) {
// return the views type
return getItem(position).getItemType();
}
#Override
public int getViewTypeCount() {
return 3; // we have 3 different item-types
}
}
/**
* generates a random ChartData object with just one DataSet
*
* #return
*/
private LineData generateDataLine(int cnt) {
ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
ArrayList<Entry> values = new ArrayList<>();
for (int z = 0; z < 3; z++) {
values = new ArrayList<Entry>();
for (int i = 0; i < 20; i++) {
double val = (Math.random() * 100) + 3;
values.add(new Entry(i, (float) val));
}
LineDataSet d = new LineDataSet(values, "DataSet" + z);
d.setLineWidth(2.5f);
d.setCircleRadius(4f);
int color = mColors[z % mColors.length];
d.setColor(color);
d.setCircleColor(color);
dataSets.add(d);
}
LineData data = new LineData(dataSets);
return data;
}
/**
* generates a random ChartData object with just one DataSet
*
* #return
*/
private ScatterData generateDataScatter(int cnt) {
ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
ArrayList<Entry> values = new ArrayList<>();
for (int z = 0; z < 3; z++) {
values = new ArrayList<Entry>();
for (int i = 0; i < 20; i++) {
double val = (Math.random() * 100) + 3;
values.add(new Entry(i, (float) val));
}
ScatterDataSet d = new ScatterDataSet(values, "DataSet" + z);
int color = mColors[z % mColors.length];
d.setColor(color);
dataSets.add(d);
}
ScatterData data = new ScatterData(dataSets);
return data;
}
private int[] mColors = new int[]{
ColorTemplate.VORDIPLOM_COLORS[0],
ColorTemplate.VORDIPLOM_COLORS[1],
ColorTemplate.VORDIPLOM_COLORS[2]
};
}
Abstact of the item of list view
public abstract class ChartItem {
protected static final int TYPE_BARCHART = 0;
protected static final int TYPE_LINECHART = 1;
protected static final int TYPE_PIECHART = 2;
protected static final int TYPE_SCATTERCHART = 3;
protected ChartData<?> mChartData;
public ChartItem(ChartData<?> cd) {
this.mChartData = cd;
}
public abstract int getItemType();
public abstract View getView(int position, View convertView, Context c);
}
Implementation of one of item of list view
public class ScatterChartItem extends ChartItem implements OnChartValueSelectedListener {
private Typeface mTf;
public ScatterChart mChart;
public ScatterChartItem(ChartData<?> cd, Context c) {
super(cd);
mTf = Typeface.createFromAsset(c.getAssets(), "OpenSans-Regular.ttf");
}
#Override
public int getItemType() {
return TYPE_SCATTERCHART;
}
#Override
public View getView(int position, View convertView, Context c) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(c).inflate(
R.layout.list_item_scatterchart, null);
holder.chart = (ScatterChart) convertView.findViewById(R.id.chart);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// apply styling
// holder.chart.setValueTypeface(mTf);
holder.chart.setDescription("");
holder.chart.setDrawGridBackground(false);
XAxis xAxis = holder.chart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTTOM);
xAxis.setTypeface(mTf);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(true);
YAxis leftAxis = holder.chart.getAxisLeft();
leftAxis.setTypeface(mTf);
leftAxis.setLabelCount(5, false);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis rightAxis = holder.chart.getAxisRight();
rightAxis.setTypeface(mTf);
rightAxis.setLabelCount(5, false);
rightAxis.setDrawGridLines(false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
// set data
holder.chart.setData((ScatterData) mChartData);
// do not forget to refresh the chart
// holder.chart.invalidate();
holder.chart.animateX(750);
holder.chart.setOnChartValueSelectedListener(this);
mChart=holder.chart;
return convertView;
}
#Override
public void onValueSelected(Entry e, Highlight h) {
}
#Override
public void onNothingSelected() {
}
#Override
public void onMultipleValueSelected() {
if (mChart.end_selection) {
Highlight[] high= mChart.getHighlighted();
ListViewMultiChartActivity.chart.mChart.highlightValues(high);
ListViewMultiChartActivity.check_button.setVisibility(View.VISIBLE);
ListViewMultiChartActivity.close_button.setVisibility(View.VISIBLE);
}else{
ListViewMultiChartActivity.check_button.setVisibility(View.INVISIBLE);
ListViewMultiChartActivity.close_button.setVisibility(View.INVISIBLE);
}
}
private static class ViewHolder {
ScatterChart chart;
}
}
I use the MPAndroidChart, here there is the class where i set the gesture of the chart
I have 3 components in my layout ListView, EditText, Button.
When the user enters text in the edittext and hits the Button, the app makes an Api call, my just added text is added to an existing list,and fetches the list of items. Now, my issue is that that the api call is successful and I get the list with my new item properly. But when I show it in the listview, the first item in the ListView is never visible. The text I add after the first text are visible properly, even if I have a list of 10 or more items, the first item never shows. Also, Iam showing the listview and other components inside a scrollview to take full length.
Here is my code:-
public class ItemListAdapter : BaseAdapter
{
public ItemListAdapter(Activities.Detail detail, List<Models.ListOfItems> itemList)
{
// TODO: Complete member initialization
this.detail = detail;
this.itemList = itemList;
inflater = detail.LayoutInflater;
}
public override int Count
{
get { return itemList.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return position;
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.Inflate(Resource.Layout.item_row_layout, null);
}
txtAuthorName = convertView.FindViewById<TextView>(Resource.Id.txtCommentAuthor);
txtItemName = convertView.FindViewById<TextView>(Resource.Id.txtTime);
txtItemDate = convertView.FindViewById<TextView>(Resource.Id.txtItemDate);
var mData = itemList.ElementAt(position);
txtAuthorName.Text = mData.AuthorDisplayName;
txtItemName.Text = DateTime.Parse(mData.DateUpdated).ToString("dd MMMM yyyy", CultureInfo.InvariantCulture);
txtItemDate.Text = mData.Text;
return convertView;
}
}
Code for listview to take full height :-
public static void SetListViewHeightBasedOnChildren(ListView listView)
{
IListAdapter listAdapter = listView.Adapter;
if (listAdapter == null)
return;
int desiredWidth = Android.Views.View.MeasureSpec.MakeMeasureSpec(listView.Width, MeasureSpecMode.Unspecified);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.Count; i++)
{
view = listAdapter.GetView(i, view, listView);
if (i == 0)
view.LayoutParameters = new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WrapContent);
totalHeight += view.MeasuredHeight;
view.Measure(desiredWidth, totalHeight);
}
ViewGroup.LayoutParams param = listView.LayoutParameters;
param.Height = totalHeight + (listView.DividerHeight * (listAdapter.Count - 1));
listView.LayoutParameters = param;
listView.RequestLayout();
}
Try the below code may be its because of divider height. Have you defined custom height for divider in your listview?.
/**
* Sets ListView height dynamically based on the height of the items.
*
* #param listView to be resized
*
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
float singleViewHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
singleViewHeight = listItem.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(listAdapter.getCount() - 1);
// Set list height
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + totalDividersHeight + (Math.round(singleViewHeight / 2));
listView.setLayoutParams(params);
listView.requestLayout();
}
I have created a GridView control, which inhertis from a ScrollView, the idea of this control, is that it will contain multiple Views arranged in a grid format with a given number of columns and rows.
When the view is first built, the GridView doesn't know the size of its container, so I wait until the onSizeChanged method is called, then I apply the relevant sizing.
When the below is run, it doesn't re-size the grid to show it correctly, each control is only as big as it needs to be to show the text.
When the `onSizeChanged' method is called, it has the correct size, and applies the correct size to each child view, but it doesn't affect the way the controls are drawn (i.e. they're still all bunched up on the top left of the screen).
Despite this, I have actually got it working, but it draws twice. I do this by creating a Runnable which calls ResizeList. Then calling new Handler().post(r) straight after I call BuildIt.
Although this is a solution, I just don't understand why it doesn't work in the below form.
Incidentally, if the GridView is the main View added to the Activity, it displays fine, it's only when it's subsequently added. Which is why I have the Button, which you have to press to show the grid.
Can anyone suggest why the below code doesn't work properly?
public class MainActivity extends Activity {
GridView sv;
FrameLayout flay;
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
flay=new FrameLayout(this);
this.setContentView(flay);
Button b=new Button(this);
b.setText("press me to show grid view");
b.setOnClickListener(ocl);
flay.addView(b);
}
OnClickListener ocl=new OnClickListener()
{
#Override public void onClick(View v)
{
BuildIt();
}};
private void BuildIt()
{
flay.removeAllViews(); // remove the button control
sv=new GridView(this);
for (int c1=0 ; c1<30 ; c1++)
{
TextView tv=new TextView(this);
tv.setText("Item "+c1);
tv.setGravity(android.view.Gravity.CENTER);
sv.addListItem(tv);
}
flay.addView(sv);
sv.ConstructList();
}
}
The GridView class
public class GridView extends ScrollView
{
final int rows=4;
final int cols=4;
private ArrayList<View> allViews=new ArrayList<View>();
private LinearLayout ll;
public GridView(Context context)
{
super(context);
ll=new LinearLayout(context);
ll.setOrientation(LinearLayout.VERTICAL);
this.addView(ll);
}
public void addListItem(View v)
{
allViews.add(v);
}
public void ConstructList()
{
int c1=0;
ll.removeAllViews(); // Just in case we're re-building
LinearLayout row=null;
for (View v : allViews)
{
if (c1%cols==0)
{
row=new LinearLayout(this.getContext());
ll.addView(row);
}
row.addView(v);
c1++;
}
}
private void ResizeList()
{
int useHeight=getHeight()/rows;
int useWidth=getWidth()/cols;
LinearLayout.LayoutParams lpCol=new LinearLayout.LayoutParams(useWidth, useHeight);
Log.i("log","About to set width/height="+useWidth+"/"+useHeight);
int numKids= ll.getChildCount();
for (int c1=0 ; c1<numKids ; c1++)
{
LinearLayout ll2=(LinearLayout)ll.getChildAt(c1);
for (int c2=0 ; c2<ll2.getChildCount() ; c2++) // use getChildCount rather than cols, just in case it's the last one
{
View v=ll2.getChildAt(c2);
v.setLayoutParams(lpCol);
}
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
ResizeList();
}
}
I have a function which is used to resize the child's width and height in gridView.
May be this could help you :
public static void setGridChild_Height(GridView gridView, int columns) {
ListAdapter listAdapter = gridView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int items = listAdapter.getCount();
int rows = 0;
for (int j = 0; j < items; j++) {
View view = gridView.getChildAt(j);
if (view != null && view.getHeight() > totalHeight) {
totalHeight = view.getHeight();
}
}
System.out.println("totalHeight -> " + totalHeight);
if (totalHeight > 0) {
for (int j = 0; j < items; j++) {
View view = gridView.getChildAt(j);
if (view != null && view.getHeight() < totalHeight) {
view.setMinimumHeight(totalHeight);
}
}
}
// View listItem = listAdapter.getView(0, null, gridView);
// listItem.measure(0, 0);
// totalHeight = listItem.getMeasuredHeight();
//
// float x = 1;
// if (items > columns) {
// x = items / columns;
// rows = (int) (x + 1);
// totalHeight *= rows;
// }
//
// ViewGroup.LayoutParams params = gridView.getLayoutParams();
// params.height = totalHeight;
// gridView.setLayoutParams(params);
}
Try to change logic as per your requirement.
Code is not tested perfectly.
It's because onSizeChanged when newly added to the view hierarchy uses it's old sizes of "0" (according to the docs: http://developer.android.com/reference/android/view/View.html#onSizeChanged(int, int, int, int))
I think what you want is to a addOnLayoutChangedListener : http://developer.android.com/reference/android/view/View.html#addOnLayoutChangeListener(android.view.View.OnLayoutChangeListener)
Using the ViewTreeObserver might be another option that will work for you: How can you tell when a layout has been drawn?
I'm getting an Illegal Argument Exception when running this Activity. Could someone point out why? My comment about the Specs will hopefully lead you to my misunderstanding of this code:
[Activity(Label = "Views/Layouts/GridLayout/3. Form (Java)", MainLauncher = true)]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new string[] { })]
public class GridLayout3 : Activity {
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
SetContentView(Grid(this));
//SetContentView (Create (this));
}
public static View Grid(Context context) {
GridLayout gL = new GridLayout(context);
gL.AlignmentMode = GridAlign.Bounds;
gL.UseDefaultMargins = true;
//gL.ColumnOrderPreserved = false;
//gL.RowOrderPreserved = false;
gL.RowCount = 5;
gL.ColumnCount = 5;
//I want these Specs to tell the View to take up 2 rows of space.
//IE, (row 0-indexed) of 3 and 4 in column 4 should contain
//the same button
GridLayout.Spec specialRowSpec = GridLayout.InvokeSpec(3, 4);
GridLayout.Spec specialColSpec = GridLayout.InvokeSpec(4);
bool keyIsSpecial = false;
for (int i = 0; i < gL.RowCount; i++) {
GridLayout.Spec row = GridLayout.InvokeSpec(i);
for (int v = 0; v < gL.ColumnCount; v++) {
GridLayout.Spec col = GridLayout.InvokeSpec(v);
Button bt = new Button(context);
bt.Text = "Tester";
if (i == 3 && v == 4) {
keyIsSpecial = true;
}
if (keyIsSpecial) {
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.RowSpec = specialRowSpec;
param.ColumnSpec = specialColSpec;
param.Height = 100;
gL.AddView(bt, new GridLayout.LayoutParams(param));
return gL;
} else {
gL.AddView(bt, new GridLayout.LayoutParams(row, col));
}
if (v == gL.ColumnCount - 1) {
v = 0;
break;
}
}
}
return gL;
}
The exception is thrown when I add the view with the special Specs: gL.AddView(bt, new GridLayout.LayoutParams(param));
Here's the link to the GridLayout.Spec documentation that I may be misunderstanding: http://developer.android.com/reference/android/widget/GridLayout.Spec.html
I've also tried exchanging the second argument to my specialRowSpec to use total size (height) instead of the index of the row. For example: GridLayout.Spec specialRowSpec = GridLayout.InvokeSpec(3, 2); This just gives me a 5 by 5 grid of buttons with no buttons spanning multiple rows.
Any questions?