Android - How to set margin to custom LinearLayouts in GridLayout? - android

I have problems with setting margin to a custom made linear layout class that I use multiple times in a GridLayout. The Gridlayout is placed in a fragment.
This is the code of fragment_grid.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app_a_tize.expressme.Fragment.GridFragment"
android:layout_gravity="center">
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/orange"
android:layout_margin="5dp"
android:id="#+id/gridlayout_grid"></GridLayout>
</FrameLayout>
This is the code of the GridFragment.java:
public class GridFragment extends Fragment {
public GridFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_grid, container, false);
}
#Override
public void onStart() {
super.onStart();
GridLayout grid = (GridLayout) getView().findViewById(R.id.gridlayout_grid);
grid.setRowCount(3);
int tileHeight = (CategoryTileActivity.gridContentHeight -3 * 10) / 3;
int amountofColumns = (int) CategoryTileActivity.gridContentWidth / tileHeight;
grid.setColumnCount(amountofColumns);
grid.setMinimumWidth((amountofColumns * tileHeight) + (5 * 20 ));
for (int i = 0; i < 3 * amountofColumns; i++) {
//fill the grid with the custom LinearLayout:
grid.addView(new TileClass(getActivity(), tileHeight, tileHeight, "ToBeImplemented", "Button"));
}
}
}
This is the code of the custom LinearLayout:
public class TileClass extends LinearLayout {
public TileClass(Context context, int height, int width, String image, String text) {
super(context);
this.setBackgroundResource(R.drawable.tile_button); //creates rounded layouts
this.setMinimumHeight(height);
this.setMinimumWidth(width);
this.setOrientation(LinearLayout.VERTICAL);
ImageView tileImage = new ImageView(context);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.tilephoto);
Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 100, 100, true);
tileImage.setImageBitmap(bMapScaled);
tileImage.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView tileText = new TextView(context);
tileText.setText(text);
tileText.setTextColor(Color.WHITE);
tileText.setGravity(Gravity.CENTER);
addView(tileImage);
addView(tileText);
}
}
When I run the Activity, I get this as result:
The code I showed above is responsible for the orange area in the middle. What I need: the blue "buttons"/LinearLayouts, in the orange area in the middle, to have a margin of 5dp. So the rest of the orange space is be taken by the custom LinearLayouts.
I don't know how to fix that, I tried a lot of options but they don't seem to work out for me.. Everything from MarginLayoutParams to params.setMargins(5,5,5,5); On almost every layout in my code.
I use Android Studio 2.1.2, supporting minimum of API 15.
Every help is appreciated!
For your imagination, this must be the end result, I need the margin like this:

You have to make custom view of gridview item as below:-
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/categoryHeight"
android:layout_marginLeft="#dimen/margin_5dp"
android:layout_marginRight="#dimen/margin_5dp"
android:layout_marginTop="#dimen/margin_7dp"
android:background="#drawable/rounded_bg"
>
<ImageView
android:id="#+id/llRowItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scaleType="fitXY"
android:gravity="bottom"/>
<TextView
android:id="#+id/item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black_light"
android:padding="#dimen/margin_5dp"
android:layout_gravity="bottom"
android:singleLine="true"
android:textColor="#color/white"
android:textSize="#dimen/font_size_16sp" />
</FrameLayout>
and inside adapter set color of text view, background, text or image of imageview whatever you want to set.

Related

How to fit a LinearLayout in a ScrollView?

Earlier on I asked a question about how to reach the last item of a scrollview and someone pointed out that I should be using NestedScrollView, at first it worked but now it's not what I want.
I want to fit my list of item in the ScrollView so only that part of the screen can be scrolled and the other parts stay at their place (the 3 TextView)
So basically my xml file is like this :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/cl_framgnent_detail_apero"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
tools:context=".ui.home.AperoDetailFragment">
<TextView
android:id="#+id/name_apero"
/>
<TextView
android:id="#+id/date_apero"
/>
<TextView
android:id="#+id/ingredient_title_apero"
/>
<ScrollView
android:id="#+id/rv_apero_ingredient"
android:layout_width="408dp"
android:layout_height="603dp"
android:fillViewport="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/ingredient_title_apero"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/ingredient_title_apero"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:id="#+id/vertical_layout_ingredient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
And in my Java code I try to populate my list with the following code :
public class AperoDetailFragment extends Fragment {
private View root;
private Apero detailApero;
public AperoDetailFragment(Apero apero) {
this.detailApero = apero;
}
#Override
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_detail_apero, container, false);
TextView name = (TextView) root.findViewById(R.id.name_apero);
name.setText(detailApero.getName());
TextView date = (TextView) root.findViewById(R.id.date_apero);
date.setText(detailApero.getDate());
LinearLayout ll = (LinearLayout) root.findViewById(R.id.vertical_layout_ingredient);
LinearLayout a = new LinearLayout(root.getContext());
ConstraintLayout.LayoutParams lparams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT);
a.setLayoutParams(lparams);
a.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 20; i++) {
Button b = new Button(root.getContext());
b.setText("Button " + i);
a.addView(b);
}
ll.addView(a);
return root;
}
}
The problem is that the item are covering the whole screen instead of staying in the parent container (ScrollView) :
How can I fit my list of item to stay in the parent ?
If this is your actual code, then it might help to set constraints to the text views too.
Also, if your ScrollView has a fixed height, then you should remove either the top or bottom constraint. So if you want it to stick to the bottom, remove the top constraint.
I solved this with removing the ScrollView and using a ListView

Get the position of each corner of a view, then add a view at the position

I am working on an android project where I have a custom view. When the custom view is clicked, I want a to put a view (a circle) at each corner of the view.
At the moment I'm just trying to get it work in the top left corner but it ends up in the middle.
Below is my click function for adding the view.
View view = LayoutInflater.from(getContext()).inflate(R.layout.view, this, false);
TextView textItem = view.findViewById(R.id.lblItemText);
textItem.setText("View: " + counter);
view.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Anchor anchor1 = new Anchor(getContext());
anchor1.setLeft(v.getLeft());
anchor1.setTop(CustomView.this.getTop());
CustomView.this.addView(anchor1);
}
});
The custom view is hosted inside a relative layout. The custom view extends RelativeLayout and the anchor view which is supposed to go into the top left corner of the custom view extends button.
The anchor constructor contains the following:
public Anchor(Context context)
{
super(context);
this.setBackgroundResource(R.drawable.anchor);
this.setPadding(0,0,0,0);
this.setWidth(1);
this.setHeight(1);
}
For some reason the anchor is appearing in the middle instead of being on the corner as shown below
Below is kind of expecting.
UPDATE
After a couple of days made some progress and I do have it working, except its using hardcoded values to get it in the right position, which doesn't seem right. I'm guessing this will only work on the specific device I'm testing on, another device with another resolution will be positioned wrong.
Below is the code I have that hopefully shows what is I am trying to achieve along with a screenshot as to what I have now.
private void createAnchorPoints()
{
//Main View
ViewGroup mainView = activity.findViewById(android.R.id.content);
int[] viewToBeResizedLoc = new int[2];
viewToBeResized.getLocationOnScreen(viewToBeResizedLoc);
//Add top left anchor
Anchor topLeftAnchor = new Anchor(context, Anchor.ResizeMode.TOP_LEFT);
FrameLayout.LayoutParams topLeftParms = new FrameLayout.LayoutParams(150,150);
topLeftParms.leftMargin = viewToBeResizedLoc[0] - 50;
topLeftParms.topMargin = viewToBeResizedLoc[1] - viewToBeResized.getHeight() - 30;
topLeftAnchor.setLayoutParams(topLeftParms);
mainView.addView(topLeftAnchor);
//Add top right anchor
Anchor topRightAnchor = new Anchor(context, Anchor.ResizeMode.TOP_RIGHT);
FrameLayout.LayoutParams topRightParms = new FrameLayout.LayoutParams(150, 150);
topRightParms.leftMargin = topLeftParms.leftMargin + viewToBeResized.getWidth() - 40;
topRightParms.topMargin = topLeftParms.topMargin;
topRightAnchor.setLayoutParams(topRightParms);
mainView.addView(topRightAnchor);
//Add bottom left anchor
Anchor bottomLeftAnchor = new Anchor(context, Anchor.ResizeMode.BOTTOM_LEFT);
FrameLayout.LayoutParams bottomLeftParms = new FrameLayout.LayoutParams(150, 150);
bottomLeftParms.leftMargin = topLeftParms.leftMargin;
bottomLeftParms.topMargin = topLeftParms.topMargin + viewToBeResized.getHeight() - 40;
bottomLeftAnchor.setLayoutParams(bottomLeftParms);
mainView.addView(bottomLeftAnchor);
//Add bottom right anchor
Anchor bottomRightAnchor = new Anchor(context, Anchor.ResizeMode.BOTTOM_RIGHT);
FrameLayout.LayoutParams bottomRightParms = new FrameLayout.LayoutParams(150, 150);
bottomRightParms.leftMargin = topRightParms.leftMargin;
bottomRightParms.topMargin = bottomLeftParms.topMargin;
bottomRightAnchor.setLayoutParams(bottomRightParms);
mainView.addView(bottomRightAnchor);
}
Since the top-level layout is a RelativeLayout, you will need to use the view positioning that is available to RelativeLayout to achieve what you want. (See the documentation.)
Here is a mock-up of what you want to achieve in XML. This mock-up will demonstrate how we can approach the actual solution. I am using standard views, but it shouldn't matter. The technique will apply to your custom views. The image is from Android Studio's designer, so no code was used to create the image.
activity_main.xml
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/customView"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerInParent="true"
android:background="#android:color/holo_green_light" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignStart="#id/customView"
android:layout_alignTop="#id/customView"
android:src="#drawable/circle"
android:translationX="-10dp"
android:translationY="-10dp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignEnd="#id/customView"
android:layout_alignTop="#id/customView"
android:src="#drawable/circle"
android:translationX="10dp"
android:translationY="-10dp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignBottom="#id/customView"
android:layout_alignStart="#id/customView"
android:src="#drawable/circle"
android:translationX="-10dp"
android:translationY="10dp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignBottom="#id/customView"
android:layout_alignEnd="#id/customView"
android:src="#drawable/circle"
android:translationX="10dp"
android:translationY="10dp" />
</RelativeLayout>
circle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<!-- fill color -->
<solid android:color="#android:color/holo_red_light" />
<size
android:width="20dp"
android:height="20dp" />
</shape>
The Actual Solution
Now that we have demonstrated that the mocked-up approach works, we now have to reproduce the effect in code. We will have to add the circle view and position it within the parent RelativeLayout using RelativeLayout view positioning and translations. The following code shows just the top left circle positioned, but the other circles will be positioned in a similar way.
activity_main.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Drawable circle = ContextCompat.getDrawable(this, R.drawable.circle);
ImageView imageView = new ImageView(this);
imageView.setImageDrawable(circle);
int circleSize = dpToPx(CIRCLE_SIZE_DP);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(circleSize, circleSize);
// Position top left circle within the custom view.
lp.addRule(RelativeLayout.ALIGN_START, R.id.customView);
lp.addRule(RelativeLayout.ALIGN_TOP, R.id.customView);
// Uncomment these 2 lines to position the top left circle with translation.
imageView.setTranslationX(-circleSize / 2);
imageView.setTranslationY(-circleSize / 2);
// Uncomment these 3 lines to position the top left circle with margins.
// View customView = findViewById(R.id.customView);
// lp.leftMargin = customView.getLeft() - circleSize / 2;
// lp.topMargin = customView.getTop() - circleSize / 2;
((RelativeLayout) findViewById(R.id.relativeLayout)).addView(imageView, lp);
}
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
private static final int CIRCLE_SIZE_DP = 20;
}
The code above uses a shortened layout:
activity_main.xml
<RelativeLayout
android:id="#+id/relativeLayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/customView"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_centerInParent="true"
android:background="#android:color/holo_green_light" />
</RelativeLayout>
It is also possible to produce the same positioning using margins. The code to use margins is commented out but will work. (I think that negative margins may also work, but I have read that they are not officially supported, so I try to avoid them.)

Android: how to configure sizing of a custom layout

I've been trying to create a custom horizontal layout with the goal to have a TextView to the left of an ImageView, containing a icon which depicts a certain status. The ImageView is to kept in a square dimension, with it's height and width equal to the height of the text in the TextView. Issues continue to persist, however, such as the text height not being set as specified in the layout xml file and an unknown padding existing after the ImageView. These problem can be seen in this image, with the red indicating the unknown padding and the blue indicating the text size inconsistency where both where set to 12sp. The font sizing and padding issues need to be fixed so the layout can be properly added to a grid layout, which will contain a grid of these custom layouts.
StatusIcon.java
//This is part of the java class that extends ImageView to resize the Icon
#Override
protected void onMeasure(int width, int height) {
super.onMeasure(width, height);
int measuredHeight = getMeasuredHeight();
setMeasuredDimension(measuredHeight, measuredHeight);
}
StatusIndicator.java
//This is the java class for the custom layout.
public class StatusIndicator extends LinearLayout {
private TextView label;
private StatusIcon statusLed;
private CharSequence labelText;
private float labelTextSize;
public enum Status {
GOOD,
WARNING,
CRITICAL
}
/*
* Removed the basic required class constructors to save space.
*/
private void getAttributes(Context context, AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.StatusIndicator);
labelText = typedArray.getString(R.styleable.StatusIndicator_label);
labelTextSize = typedArray.getDimensionPixelSize(R.styleable.StatusIndicator_labelSize, 0);
typedArray.recycle();
}
private void initializeViews(Context context){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_status_indicator, this);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
//Setup UI elements in layout
label = (TextView) findViewById(R.id.textView_statusIndicatorLabel);
statusLed = (StatusIcon) findViewById(R.id.imageView_statusIndicatorLed);
label.setText(labelText);
if(labelTextSize > 0){
label.setTextSize(TypedValue.COMPLEX_UNIT_SP, labelTextSize);
}
}
public void setStatus(StatusIndicator.Status status){
switch (status){
case GOOD:
statusLed.setImageResource(R.mipmap.ic_status_panel_good);
break;
case WARNING:
statusLed.setImageResource(R.mipmap.ic_status_panel_warning);
break;
case CRITICAL:
statusLed.setImageResource(R.mipmap.ic_status_panel_critical);
break;
}
}
}
view_status_indicator.xml
<?xml version="1.0" encoding="utf-8"?>
<merge 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"
tools:parentTag="LinearLayout"
tools:orientation="horizontal">
<TextView
android:id="#+id/textView_statusIndicatorLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|start"
android:layout_marginEnd="2dp"
android:text="#string/default_title"
android:textAppearance="#style/TextAppearance.AppCompat.Title"
android:textSize="12sp"/>
<com.css_design.android_quickbridge.ui.home.status_panel.StatusIcon
android:id="#+id/imageView_statusIndicatorLed"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_vertical|end"
app:srcCompat="#mipmap/ic_status_panel_critical"/>
</merge>
I would solve this problem by using ConstraintLayout instead of creating a custom view implementation.
ConstraintLayout allows you to specify an aspect ratio for its children, which takes care of wanting to make sure your ImageView is always exactly square. ConstraintLayout also allows you to specify height or width based on sibling views (by combining a dimension of 0dp with top and bottom (or left and right) constraints).
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ccf">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="0dp"
android:src="#drawable/circle"
app:layout_constraintTop_toTopOf="#+id/text"
app:layout_constraintLeft_toRightOf="#+id/text"
app:layout_constraintBottom_toBottomOf="#+id/text"
app:layout_constraintDimensionRatio="1"/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40sp"
android:text="hello world"/>
</android.support.constraint.ConstraintLayout>
(Background color added to the ConstraintLayout to show that it's not any larger than its contents).

How to show image in table row based on size

Have 2x2 grid(Dynamic using TableLayout) need to show image on that. now based on image size, means-- if image fit for 1 cell means 1 cell,else big means 2 cells or 4 cells based on size( I know how many cells it will occupy)
i can show image in 1 cell, but problem is if image need 2 cells(1st column) how can show image in 2cell(With out disturbing the grid)
Without disturbing the grid, the workaround I see is to dynamically set image on top of your TableLayout.
Then you can archive this:
I've uploaded the code of the test project here;
You initialize overlappingImage and once you need to set image to your cell - you just add it to the layout and setting height and width params based on number of cells you want to fill.
TableLayout generates dynamically, the cell's layout xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<View
android:layout_margin="4dp"
android:background="#aacc00"
android:layout_height="40dp"
android:layout_width="40dp"/>
</FrameLayout>
The Activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
android:padding="16dp"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="280dp"/>
<LinearLayout
android:id="#+id/buttonsLinearLayout"
android:layout_below="#+id/tableLayout"
android:layout_marginTop="16dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="1x1"
android:id="#+id/button11"
android:onClick="onClick11"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="4x1"
android:id="#+id/button21"
android:onClick="onClick41"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="2x3 at (2;2)"
android:id="#+id/button12"
android:onClick="onClick32"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="2x2"
android:id="#+id/button22"
android:onClick="onClick22"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
And the Activity code to handle button clicks & generates table:
public class MainActivity extends AppCompatActivity {
RelativeLayout container;
int cellWidth = 0, cellHeight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
tableLayout.setStretchAllColumns(true);
for (int i = 0; i < 4; i++) {
TableRow tableRow = new TableRow(this);
for (int j = 0; j < 10; j++) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cell = layoutInflater.inflate(R.layout.table_cell, null, false);
if (cellHeight == 0 ) {
cell.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
cellWidth = cell.getMeasuredWidth();
cellHeight = cell.getMeasuredHeight();
}
tableRow.addView(cell);
}
tableLayout.addView(tableRow);
}
container = (RelativeLayout)findViewById(R.id.container);
overlappingImage = new ImageView(this);
overlappingImage.setScaleType(ImageView.ScaleType.FIT_XY);
}
ImageView overlappingImage;
private void restoreTableLayout() {
container.removeView(overlappingImage);
}
public void onClick11(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth, cellHeight);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
public void onClick41(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*4, cellHeight);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
public void onClick32(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*3, cellHeight*2);
params.setMargins(cellWidth*2, cellHeight*2, 0 ,0);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.vertical_cat);
container.addView(overlappingImage);
}
public void onClick22(View view) {
restoreTableLayout();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(cellWidth*2, cellHeight*2);
overlappingImage.setLayoutParams(params);
overlappingImage.setImageResource(R.drawable.horizontal_cat);
container.addView(overlappingImage);
}
}
I hope, it helps.
Create separate layout files for rows that would need one cell and two cell as follows:
one_cell_table_row.xml (Notice the android:layout_span="2" for the ImageView
<?xml version="1.0" encoding="utf-8"?>
<TableRow
android:background="#drawable/bg_gray"
android:layout_marginTop="5dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/imgMyImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_span="2" />
</TableRow>
two_cell_table_row.xml (The TextView placed just as a placeholder for the second cell) (No layout_span required here as in the above layout)
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/imgMyImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_weight="1"
android:text="..."
android:textColor="#767575"
android:id="#+id/txtJustAPlaceholder"
android:textSize="14dp" />
</TableRow>
Note: The id for the ImageView to be kept same in both layout for the java code below to work correctly.
The above is assuming your grid is 2x2. If your grid size is different create more layout for each kind of row you want and add extra conditions in the java code below.
Adding the TableRow with the right layout inflated:
Then programatically determine which layout needs to be inflated. Inflate the required layout for table row and add it to your table layout:
Following code is assuming that you are using a fragnemt. If you are doing directly in an activity replace code to work for Activity accordingly.
TableLayout table = (TableLayout) getView().findViewById(R.id.youtTableLayout);
if(<your image size needs two cells>) {
TableRow row = (TableRow) LayoutInflater.from(getActivity().getApplicationContext())
.inflate(R.layout.two_cell_table_row, null);
}
else if(<your image size needs one cell) {
TableRow row = (TableRow) LayoutInflater.from(getActivity().getApplicationContext())
.inflate(R.layout.one_cell_table_row, null);
}
...
...
// add more conditions and respective layouts as you need.
...
...
ImageView myImgView = (ImageView) row.findViewById(R.id.txtCrdSectionHeader);
// set the image for your image view here.
table.addView(row);
table.requestLayout();
Again, the above was assuming that your TableLayout has a 2x2 grid. If you plan to use a different one, update the layout files for TableRows we created above accordingly or set them dynamically using your java code.
You can calculate the image size and the screen size at runtime.Based on the calculations you can set the table properties at runtime. For example if the image is going to take two columns set the span property on that row programmatically.
I would suggest for your requirement you can consider creating the layout in code itself-rather than using any xml.
You can also have a look at Recycler view. It has more powerful ways to control the layout of the children. Have a look at this video-Mastering Recycler View -It is trying to do similar thing what you are looking for.

Issue resizing ImageView programmatically

I am stuck trying to resize ImageView objects.
The issue is that when I set the width/height programmatically, I see the width/height change with the debugger tool in eclipse.
However, the image will not scale to the new size, and maintains its current ratios. In some cases it even puts the original image at its current size, and moving to a different activity will resize it (somewhat) correctly.
Screenshots:
After opening the app
http://imgur.com/ha9s9rL
After opening and closing a different activity
http://imgur.com/DrBIJaI
I would like for the images to sit next to each other, with the same width/height for each image.
onCreate() Method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_behavior);
listView = (ListView) findViewById(R.id.display_behavior_listview);
List<Behavior> behaviorList = parseCatagories();
List<View> views = getCatagoryViewsFromBehaviorList(behaviorList);
// Setup array adapter
BehaviorRow behaviorRows[] = getBehaviorRows(views);
int viewCount = 0;
View view;
for (BehaviorRow row : behaviorRows) {
if (viewCount < views.size()) {
view = views.get(viewCount);
row.setBehaviorOne(view);
viewCount++;
view = views.get(viewCount);
row.setBehaviorTwo(view);
viewCount++;
}
Log.i("BehaviorRowDat", row.toString());
}
BehaviorRowAdapter adapter = new BehaviorRowAdapter(getApplicationContext(), R.layout.catagory_row,
behaviorRows);
listView.setAdapter(adapter);
}
onWindowFocusChanged() Method:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ImageView catagoryOne;
ImageView catagoryTwo;
for (int i = 0; i < listView.getChildCount(); i++) {
catagoryOne = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_one);
catagoryTwo = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_two);
resizeImageView(catagoryOne);
resizeImageView(catagoryTwo);
}
}
Resize Image Code:
private ImageView resizeImageView(ImageView image) {
// Set length/width
int length = calculateLengthOfImages();
image.getLayoutParams().height = length;
image.getLayoutParams().width = length;
// Set Padding
int padding = calculatePaddingOfImages();
image.setPadding(padding, padding, padding, padding);
return image;
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
</LinearLayout>
Try changing the scaleType attribute in your ImageViews to:
android:scaleType="fitXY"
Alternatively, you can add this line in your resizeImageView() method:
image.setScaleType(ScaleType.FIT_XY);
Hope that helps!
Replace your xml with this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:scaleType="centerCrop" />
</LinearLayout>
In onCreate() of your activity, add this:
final ImageView imageView1 = (ImageView) findViewById(R.id.catagory_space_one);
final ImageView imageView2 = (ImageView) findViewById(R.id.catagory_space_two);
imageView1.post(new Runnable() {
#Override
public void run() {
imageView1.getLayoutParams().height = imageView1.getWidth();
imageView1.requestLayout();
}
});
imageView2.post(new Runnable() {
#Override
public void run() {
imageView2.getLayoutParams().height = imageView2.getWidth();
imageView2.requestLayout();
}
});
So what basically I did is I have stretched the two images' width equally to take the whole space in xml using layout_weight, then I have set the images' height to be like their respective widths in code. So now they are square-shaped.
Hope that helps.

Categories

Resources