How can I prevent an ImageView from resizing its parent? [duplicate] - android

This question already has answers here:
Scale Image to fill ImageView width and keep aspect ratio
(16 answers)
Closed 5 years ago.
Note: I have checked this question, but none of the answers helped. I'm restating the question to specify my specific problems and needs.
I've made a custom view in my android app that displays data for an upcoming event (title, location, price, description, etc). In addition to this data, there are also icon and cover photos displayed on this view (the icon is displayed in an ImageView in the upper-left corner of the view and the cover is modified to have an alpha of 128, then displayed behind the content of the view. Here's my layout so far:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/eventview_main" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:background="#color/color_black" android:elevation="16dp">
<!-- OBJECT IN QUESTION -->
<ImageView
android:id="#+id/eventview_cover"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="false"
android:cropToPadding="false"
android:scaleType="centerCrop" />
<ImageView android:id="#+id/eventview_icon"
android:layout_width="100dp" android:layout_height="100dp"
android:layout_marginLeft="#dimen/half_margin"
android:layout_marginRight="#dimen/half_margin"
android:layout_marginTop="#dimen/half_margin" android:elevation="8dp" />
<TextView android:id="#+id/eventview_title"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignLeft="#+id/eventview_price"
android:layout_alignParentEnd="true" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" android:layout_marginTop="#dimen/half_margin"
android:layout_toEndOf="#+id/eventview_icon" android:layout_toRightOf="#+id/eventview_icon"
android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/color_white" />
<TextView android:id="#+id/eventview_location"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentEnd="true" android:layout_alignParentRight="true"
android:layout_below="#+id/eventview_price" android:layout_toEndOf="#+id/eventview_icon"
android:layout_toRightOf="#+id/eventview_icon" android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/color_white" />
<TextView android:id="#+id/eventview_price"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentEnd="true" android:layout_alignParentRight="true"
android:layout_below="#+id/eventview_title" android:layout_toEndOf="#+id/eventview_icon"
android:layout_toRightOf="#+id/eventview_icon" android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/color_white" />
<TextView android:id="#+id/eventview_shortdesc"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignLeft="#+id/eventview_title"
android:layout_alignParentEnd="true" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true" android:layout_alignStart="#+id/eventview_title"
android:layout_below="#+id/eventview_icon"
android:layout_marginBottom="#dimen/half_margin"
android:layout_marginLeft="#dimen/half_margin" android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/color_white" android:width="0dip" />
</RelativeLayout>
When an Activity instantiates my view, it must supply a source for the data (a custom class). It is then (under setSource()) that a method updateLayout() is called, which sets the icon image, and the various TextViews. Additionally, it sets the eventview_cover's source to a BitmapDrawable (to modify the original photo's alpha). That, in turn, extends the height of the view (which I want to avoid). The height of the view should only be governed by the heights of the TextViews and the ImageView for the icon. Here's the code for EventView:
public class EventView extends RelativeLayout {
private MergeEvent src = null;
public MergeEvent getSource() {
return src;
}
protected void setSource(MergeEvent e) {
src = e;
//The data was updated, so we need to update the view!
updateLayout();
}
public EventView(MergeEvent src, Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setSource(src);
}
public EventView(MergeEvent src, Context context, AttributeSet attrs) {
super(context, attrs);
setSource(src);
}
public EventView(MergeEvent src, Context context) {
super(context);
setSource(src);
}
protected void updateLayout() {
if (getSource() != null) {
//Get source data.
MergeEvent src = getSource();
//Set the layout.
View.inflate(getContext(), R.layout.eventview, this);
//Get references to the TextViews and ImageViews
TextView title = (TextView)findViewById(R.id.eventview_title),
price = (TextView)findViewById(R.id.eventview_price),
location = (TextView)findViewById(R.id.eventview_location),
shortdesc = (TextView)findViewById(R.id.eventview_shortdesc);
ImageView icon = (ImageView)findViewById(R.id.eventview_icon),
cover = (ImageView)findViewById(R.id.eventview_cover);
icon.setImageBitmap(src.getIcon());
title.setText(src.getTitle());
price.setText("$" + src.getPrice());
location.setText(src.getLocation());
shortdesc.setText(src.getShortDescription());
//Create a new BitmapDrawable from the source's cover (a Bitmap)
BitmapDrawable bd = new BitmapDrawable(getResources(), src.getCover());
bd.setAlpha(128);
bkg.setImageDrawable(bd);
requestLayout();
}
}
}
This all works, but it resizes the view to make room for the cover photo, which again, I want to avoid. I tried using getHeight() before I set the drawable, then set the drawable, and set the cover's ImageView's height with bkg.getLayoutParams().height = height, but the call to getHeight() returned 0 because the view is technically not visible at this point, so the cover photo was invisible. The view should look like this, where the background image is cropped and centered:
tl;dr/summary:
How can I prevent an ImageView from resizing its parent?

I found this answer on another question very similar to mine:
This needs to be done using code. You need to call those size APIs a few milliseconds after the screen renders. So, if you call it 100 milliseconds after, using postDelayed method of any view that has been rendered, you will get the sizes.
Using that, I modified my updateLayout() method to this:
protected void updateLayout() {
if (getSource() != null) {
MergeEvent src = getSource();
View.inflate(getContext(), R.layout.eventview, this);
TextView title = (TextView)findViewById(R.id.eventview_title);
TextView price = (TextView)findViewById(R.id.eventview_price);
TextView location = (TextView)findViewById(R.id.eventview_location);
TextView shortdesc = (TextView)findViewById(R.id.eventview_shortdesc);
ImageView i = (ImageView)findViewById(R.id.eventview_icon);
i.setImageBitmap(src.getIcon());
title.setText(src.getTitle());
price.setText("$" + src.getPrice());
location.setText(src.getLocation());
shortdesc.setText(src.getShortDescription());
//use postDelay to set the ImageView's source and max size after 100 miliseconds (plenty of time for the UI to be drawn)
this.postDelayed(new Runnable() {
#Override
public void run() {
BitmapDrawable bd = new BitmapDrawable(getResources(), src.getCover());
bd.setAlpha(128);
ImageView bkg = (ImageView)findViewById(R.id.eventview_cover);
bkg.setMaxHeight(getHeight());
bkg.setImageDrawable(bd);
}
}, 100);
requestLayout();
}
}

Related

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 represent circle border with multiple colors in android

I am looking for a custom widget to draw a circle with multiple border colors.
Say for example if my total circle represent 0-360, I need to color my circle border with different colors.
For example, I need to mark 0-60 with red, 61-120 with green, 121-300 with magenta and 301-360 with yellow border color.
please suggest me how I can do it in android.
You application is pretty simple. I don't recommend your using an external library. You can quickly implement a class that draws and manages your desired shape. An example is presented:
public class DifferentColorCircularBorder{
private RelativeLayout parentLayout;
public DifferentColorCircularBorder(RelativeLayout parentLayout) {
this.parentLayout = parentLayout;
}
public void addBorderPortion(Context context, int color, int startDegree, int endDegree) {
ProgressBar portion = getBorderPortion(context, color, startDegree, endDegree);
parentLayout.addView(portion);
}
private ProgressBar getBorderPortion(Context context, int color, int startDegree, int endDegree) {
LayoutInflater inflater = LayoutInflater.from(context);
ProgressBar portion = (ProgressBar) inflater.inflate(R.layout.border_portion, parentLayout, false);
portion.setRotation(startDegree);
portion.setProgress(endDegree - startDegree);
portion.getProgressDrawable().setColorFilter(color, Mode.SRC_ATOP);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) portion.getLayoutParams();
params.addRule(RelativeLayout.CENTER_IN_PARENT);
portion.setLayoutParams(params);
return portion;
}
}
border_portion is defined as below:
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="220dp"
android:layout_height="220dp"
android:progressDrawable="#drawable/circle_exterior"
android:layout_centerInParent="true"
android:max="360"/>
circle_exterior is defined here:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadius="100dp"
android:thickness="10dp" >
<solid android:color="#ff111111" />
</shape>
The MainActivity class is defined like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout interiorLayout = (RelativeLayout) findViewById(R.id.interior);
DifferentColorCircularBorder border = new DifferentColorCircularBorder(interiorLayout);
border.addBorderPortion(getApplicationContext(), Color.RED, 0, 40);
border.addBorderPortion(getApplicationContext(), Color.GREEN, 40, 90);
border.addBorderPortion(getApplicationContext(), Color.BLUE, 90, 270);
border.addBorderPortion(getApplicationContext(), 0xFF123456, 270, 360);
}
}
finally activity_main layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<RelativeLayout
android:id="#+id/interior"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<View
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#drawable/circle_interior_bg"
android:layout_centerInParent="true" />
</RelativeLayout>
</RelativeLayout>
Explanation about the dimensions: This is an example. Here, I have picked the dimensions to fit the circle perfectly. Change these based on your application.
Image sample:
i just created a simple Library for that purpose CircularStatusView , it was inspired by WhatsApp Status and it's easy to use.
first up add the view, in my case i've added it around CircleImageView but you can use on any view.
<RelativeLayout
android:id="#+id/image_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
android:padding="6dp"
android:src="#mipmap/ic_launcher" />
<com.devlomi.circularstatusview.CircularStatusView
android:id="#+id/circular_status_view"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
app:portion_color="#color/colorAccent"
app:portion_spacing="4dp"
app:portion_width="4dp"
app:portions_count="8" />
</RelativeLayout>
you can set the portions count Programmatically by using:
circularStatusView.setPortionsCount(count);
and for the portions color:
circularStatusView.setPortionsColor(color);
you can also set specific color for every portion:
circularStatusView.setPortionColorForIndex(/*index of portions starting from first portion at the top CW */ i, color);
for this you can try this library that i had come across
https://github.com/mucahitsidimi/GaugeView might be useful.
uses a custom view of fixed lengths to render the circle by using canvas

Changing width of individual items in a listview

So I've searched around for an answer or a possible solution to this problem for a couple weeks now and still haven't gotten any farther. I'm working on building an app that rewards users with points after certain things. One of the pages they can visit is a leader board based off of the friends the user has.
I'm able to implement the leader board and print the users in order based off of their points, but can't implement a bar graph style look. Like So: http://imgur.com/tF51RsA
(Had to post a link because I can't paste a picture in here)
Here is what I've tried so far:
1. Adding a to xml and trying to getLayoutParams in the custom adapter then set the width, which didn't work.
2. using onDraw to draw a rectangle over top of the list item.
Here is my Leader board xml file (or close to it):
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/leader_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top"
android:background="#00000000">
</LinearLayout>
My listview row xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/user_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_default_user"/>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="10dp"
android:layout_toRightOf="#+id/user_image"/>
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="20dp"
android:textSize="16sp"
android:layout_toRightOf="#+id/rank"/>
<TextView
android:id="#+id/score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/user_name"
android:gravity="right"
android:paddingRight="15dp"/>
</RelativeLayout>
</FrameLayout>
and my custom ArrayAdapter in my leaderboard class
public class LeaderAdapter extends ArrayAdapter<LeaderboardDM>{
ArrayList<LeaderboardDM> leaders;
int layoutResourceId;
public LeaderAdapter(Context context, int layoutResourceId, ArrayList<LeaderboardDM> leaders){
super(context, layoutResourceId, leaders);
this.leaders = new ArrayList<LeaderboardDM>();
this.leaders = leaders;
this.layoutResourceId = layoutResourceId;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
ViewHolder viewHolder = null;
if(v == null){
v = getLayoutInflater().inflate(layoutResourceId, null, false);
viewHolder = new ViewHolder();
viewHolder.userImage = (ImageView) v.findViewById(R.id.user_image);
viewHolder.rank = (TextView) v.findViewById(R.id.rank);
viewHolder.userName = (TextView) v.findViewById(R.id.user_name);
viewHolder.score = (TextView) v.findViewById(R.id.score);
v.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) v.getTag();
}
LeaderboardDM lead = leaders.get(position);
if(lead != null){
//doesn't set user image yet
viewHolder.userName.setText(lead.user);
viewHolder.score.setText(String.valueOf(lead.points));
viewHolder.rank.setText("#"+String.valueOf(position+1));
}
return v;
}
class ViewHolder{
ImageView userImage;
TextView rank, userName, score;
}
}
and the leaderboardDM class
public class LeaderboardDM{
public String user;
public int points;
public String profilePicUrl;
public void setUserName(String user){
this.user = user;
}
public String getUserName(){
return user;
}
public void setPoints(int points){
this.points = points;
}
public int getPoints(){
return points;
}
public void setProfilePic(String url){
this.profilePicUrl = url;
}
public String getProfilePicUrl(){
return profilePicUrl;
}
}
The list gets sorted through using a comparator and again prints in order of their score. If anyone has an idea on how to create something like this please help point me in the right direction.
Thanks!
Edit:
Thanks to #Ridcully I was able to solve this issue.
The solution worked perfectly for anyone in the future that may do this, was to create a custom progress bar and get the drawable from the resources then set the ProgressDrawable to that drawable. From there I would set the width by setProgress(int width).
You could use a RelativeLayout and put a ProgressBar (with customized drawable) in the back. This way you can set the width of the bar by a simple setProgress().

How to set ImageView over ImageView in GridView

Suppose I have multiple images that I want to set on top of the other, how can I do this in GridView?
Like:
Background
ImageView1
ImageView2 at bottom-right of the ImageView2
Here is an example for what I want:
http://i.stack.imgur.com/JS36H.png
Here is my codes
Activity:
public class ImgAdapter extends BaseAdapter {
private Context mContext;
private ColorMatrixColorFilter cf;
String Questions = Question.Questions;
int level = Levels.level;
public ImgAdapter(Context c) {
mContext = c;
ColorMatrix matrix = new ColorMatrix();
//matrix.setSaturation(0); //0 means grayscale
matrix.setSaturation(0);
cf = new ColorMatrixColorFilter(matrix);
}
public int getCount() {
return ThumbIds.length;
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
SharedPreferences pref = mContext.getSharedPreferences(Questions, Context.MODE_PRIVATE);
//imageView = (ImageView) convertView;
imageView = new ImageView(mContext);
int size = mContext.getResources().getDimensionPixelSize(R.dimen.width);
imageView.setLayoutParams(new GridView.LayoutParams(size, size));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setAdjustViewBounds(true);
imageView.setImageResource(ThumbIds[position]);
if(pref.getBoolean(level+"answered"+position, false)){
//Thats the ImageView I want to set over the another ImageView
/*ImageView answ;
answ = new ImageView(mContext);
answ.setScaleType(ImageView.ScaleType.CENTER_CROP);
answ.setAdjustViewBounds(true);
answ.setImageResource(R.drawable.answered);*/
imageView.setImageResource(ThumbIds[position]+1);
}
return imageView;
}
public static Integer[] ThumbIds =
{
R.drawable.1,
R.drawable.2,
R.drawable.3,
R.drawable.4,
R.drawable.5,
R.drawable.6,
R.drawable.7
};
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/layout" >
<TextView
android:id="#+id/Correct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
<GridView
android:id="#+id/Question"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:horizontalSpacing="20dp"
android:verticalSpacing="20dp"
android:numColumns="3"
android:stretchMode="columnWidth"
tools:context=".Question" />
</LinearLayout>
In the Question activity I get the GridView
Unfortunately GridViews don't like it when cells try to overlap each other. So lets say you have a cell within a gridview that's 48x48dp. Attempting to render anything that's bigger then 48 will cause it to get clipped. So that means you'll need to do a trick of the eye sorta thing.
Lets say you want to show the main image at 48x48dp. Lets call the second guy an emblem whose 16x16dp and you want it centered at the bottom right corner of the main image. Then you'll need a cell that's about 56dp. If you bring padding or margin into the mix, you may need to adjust. Doing something akin to the following for each item's layout within the GridView should do the trick.
<FrameLayout
android:layout_width="56dp"
android:layout_height="56dp"
....any other attributes>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="left|top"
android:src="Your main image"
...any other attributes/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_gravity="right|bottom"
android:src="Your main image"
...any other attributes/>
</FrameLayout>

Android ImageButton with background, source and text

I want to create ImageButton with custom background, custom Icon and text below that icon
What I have so far is
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="140dp"
android:layout_height="120dp"
android:layout_marginLeft="3dp"
android:layout_marginBottom="6dp"
android:background="#drawable/btn_rectangle_background"
android:src="#drawable/ic_action_search"
/>
However, If I put there android:text="blablabla" it won't shows up :/
ic_action_homework is .PNG icon, but btn_rectangle_background is XML file, which defines shape
That's what I would like to achieve
1st answer:
Must be structure of layout likes here:
<LinearLayout
android:widht_layout="80dp"
android:height_layout="80dp"
android:padding="10dp"
android:gravity="center"
android:layout_gravity="center"
android:bacgkground="your_color ARGB"
>
<ImageView />
<TextView />
</LinearLayout>
or 2nd answer:
Create custom view
public class customView extends View{
public customView(Context context){
super(context);
}
public customView(Context context, String s, Drawable d){
super(context);
// Set Width&Height for this view
this.measure(80,80);
// or layout params with specified height&width for this view
Resources r = getResources();
int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, **Your width**,
r.getDisplayMetrics());
int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, **your height**,
r.getDisplayMetrics());
ViewGroup.LayoutParams pp = new ViewGroup.LayoutParams(width,height);
this.setLayoutParams(pp);
TextView _text = new TextView(context);
ImageView _image = new ImageView(context);
_text.setText(s);
_image.setBackground(d);
this.addView(_image);
this.addView(_text);
}
public customView(Context context, String s, Bitmap b){
....
_image.setImageBitmap(b);
...
}
}
also add view into root view #id=content of layout from activity:
findByView(R.id.content).addView(new customView((Context)this,"Your Text",getResources().getDrawable(R.drawable.icon));
or with parametr bitmap by path:
findByView(R.id.content).addView(new customView((Context)this,"Your Text",BitmapFactory.decodeFile("/sdcard/file.png"));

Categories

Resources