ImageView pushed out from screen - android

I'm playing around in Android and what I'm trying to achieve is a 10x10tile boardgame.
I want to read size and width of screen and then I want a square in the middle with a textViews above and below.
This is what I've done so far:
public void init(){
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}else{
Display d = w.getDefaultDisplay();
screenWidth = d.getWidth();
screenHeight = d.getHeight();
}
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView TVtop = new TextView(this.getApplicationContext());
TVtop.setHeight((screenHeight-screenWidth)/2);
TVtop.setWidth(screenWidth);
TVtop.setText("TOP");
TextView TVbot = new TextView(this.getApplicationContext());
TVbot.setHeight((screenHeight-screenWidth)/2);
TVbot.setWidth(screenWidth);
TVbot.setText("BOT");
TableLayout tableLayout = new TableLayout(this.getApplicationContext());
//Make a cube
LayoutParams tableParams = new LayoutParams(screenWidth, screenWidth);
tableLayout.setLayoutParams(tableParams);
//Populate tableLayout
for(int i = 0; i < nrOfTiles; i++){
TableRow tableRow = new TableRow(this.getApplicationContext());
for(int j = 0; j < nrOfTiles; j++){
ImageView imgView = new ImageView(this.getApplicationContext());
imgView.setImageResource(R.drawable.cell);
tableRow.addView(imgView);
}
tableLayout.addView(tableRow);
}
linearLayout.addView(TVtop);
linearLayout.addView(tableLayout);
linearLayout.addView(TVbot);
}
}
I've tried diffrent layoutparams but nothing seems to get the work done. :S
BR

Personally, I would use a RelativeLayout and setMargins for the items.
While not a direct answer to your question, the following code will display 15 icons in three rows. This should be enough to explain and get you started.
The main activity.
public class MainActivity extends Activity {
private int mWidth;
private int mTile;
private int mColMax = 5;
private Context mContext;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
// the screen width is need to work out the tile size
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Point size = new Point();
w.getDefaultDisplay().getSize(size);
mWidth = size.x;
}else{
mWidth = w.getDefaultDisplay().getWidth();
}
// how wide (and high) each icon will be to fit the screen.
mTile = (mWidth / mColMax);
setContentView(R.layout.activity_main);
// layout the icons
initUI();
}
/**
* Layout 15 icon images in three rows dynamically.
*/
private void initUI() {
// this is the layout from the XML
ViewGroup layout = (ViewGroup) findViewById(R.id.main_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int i = 0;
int row = 0;
int col = 0;
do {
params = new RelativeLayout.LayoutParams(mTile,mTile);
params.setMargins((col * mTile), (row * mTile), 0, 0);
iv = new ImageView(mContext);
iv.setAdjustViewBounds(true);
iv.setScaleType(ScaleType.FIT_CENTER);
iv.setImageResource(R.drawable.ic_launcher);
iv.setLayoutParams(params);
layout.addView(iv);
if (col == mColMax) {
row++;
col = 0;
} else {
col++;
}
} while (++i <= 16);
}
}
And the layout XML.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>

Related

Relative position of Buttons in different devices

I have a problem in relation to the relative location of Buttons in different devices. I have done a short application to show it. The Button, in relation to a red point, behaves as desire when dealing with wide measures (coordinate x). However, I don’t know why the same Button is progressively scrolling down from the red point (coordinate y) as I choose a smaller device. I choose the right size of the image for the different devices and for both, wide and height, I also choose the relative measure of the screen:
rel_btn.width = 4*width/100;
rel_btn.height = 7*height/100;
I show you the code and the resulting screen of the xlarge screen in case someone can help me:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//width and height of the screen
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) MainActivity.this.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
windowManager.getDefaultDisplay().getMetrics(metrics);
}
int width = metrics.widthPixels;
int height = metrics.heightPixels;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.test); // id del XML
RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rel_btn.width = 4*width/100; rel_btn.height = 7*height/100;
// x, y of the BUTTON
rel_btn.leftMargin = 15*width/100; rel_btn.topMargin = 66*height/100;
Button btnTag = new Button(this);
btnTag.setLayoutParams(rel_btn);
btnTag.setBackgroundColor(Color.TRANSPARENT);
btnTag.setId(0); // writes the ID
btnTag.setOnClickListener(prueba);
layout.addView(btnTag);
}
private View.OnClickListener prueba = new View.OnClickListener() {
#Override
public void onClick(View view) {
//width of the screen
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) MainActivity.this.getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
windowManager.getDefaultDisplay().getMetrics(metrics);
}
int width = metrics.widthPixels;
Button button = (Button) view;
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(Math.round((float) (0.6*width/100)), Color.BLUE);
drawable.setColor(Color.TRANSPARENT);
button.setBackgroundDrawable(drawable);
}
};
}

Trying to make ImageView Array stay in screen bound

I want to create 10 ImageViews in random position and I want them to be the same, I tried using ImageView[], I got the screen size(width and height) and created random place for each ImageView (in range of screen size). Some of the ImageViews are out of bounds as there are sometimes 7,8 ImageViews I can see. here's my code:
ImageView ball[], you;
int layoutwidth, layoutheight;
Random rand = new Random();
RelativeLayout rlt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rlt = (RelativeLayout) findViewById(R.id.rlt);
you = (ImageView) findViewById(R.id.imageView);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
layoutwidth = size.x;
layoutheight = size.y;
ball = new ImageView[11];
for (int i = 0; i < 10; i++) {
ball[i] = new ImageView(this);
ball[i].setTag(i);
ball[i].setBackgroundResource(R.mipmap.ball);
int randomx = rand.nextInt(layoutwidth+1);
int randomy = rand.nextInt(layoutheight+1);
ball[i].setX(randomx);
ball[i].setY(randomy);
rlt.addView(ball[i]);
}
}
How can I make the code work as I need it?
You can try to replace this
int randomx = rand.nextInt(layoutwidth+1);
int randomy = rand.nextInt(layoutheight+1);
ball[i].setX(randomx);
ball[i].setY(randomy);
rlt.addView(ball[i]);
with
int randomx = rand.nextInt(layoutwidth+1-widthOfImageView);
int randomy = rand.nextInt(layoutheight+1-heightOfImageView);
rlt.addView(ball[i]);
ball[i].setTranslationX(randomx);
ball[i].setTranslationY(randomy);
where widthOfImageView,heightOfImageView is imageview's width & height

Android GridLayout only shows last child

I am new to Android Development. I have been working with using a GridLayout to display Dynamically inserted ImageViews.
My issue is located in "onFocusWindowChanged" but I pasted my onCreate where I do my assignments of the images.
private List<Behavior> behaviors = null;
private static int NUM_OF_COLUMNS = 2;
private List<ImageView> images;
private GridLayout grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_behaviors);
XMLPullParserHandler parser = new XMLPullParserHandler();
try {
behaviors = parser.parse(getAssets().open("catagories.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
grid = (GridLayout) findViewById(R.id.behaviorGrid);
images = new ArrayList<ImageView>();
grid.setColumnCount(NUM_OF_COLUMNS);
grid.setRowCount(behaviors.size() / NUM_OF_COLUMNS);
for (Behavior behavior : behaviors)
images.add(this.getImageViewFromName(behavior.getName()));
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
View view = (View) findViewById(R.id.scrollView);
int width = (int) (view.getWidth() * .45);
Log.i("ViewWidth", Integer.toString(width));
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.height = width;
lp.width = width;
int childCount = images.size();
ImageView image;
for (int i = 0; i < childCount-1; i++) {
image = images.get(i);
image.setLayoutParams(lp);
grid.addView(image);
}
}
In my (short) previous experience, using
grid.add(View);
worked fine, but now I am only seeing the last child display only. Looking through the debugger I can see that the gridview is being populated with more than just the last element, as well as the last imageview.
Thank you for your help
you should create a GridLayout.LayoutParams for each ImageView:
for (int i = 0; i < childCount-1; i++) {
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.height = width;
lp.width = width;
......
}
GridLayout.LayoutParams contains location information, e.g [column:2, row:3]. In your code, all ImageViews are set the same GridLayout.LayoutParams, so they are located in the same cell(overlapping each other).
When use LinearLayout.LayoutParams instead, there is no location information in it. GridLayout will create a new GridLayout.LayoutParams for each child view, so all ImageViews use their own different GridLayout.LayoutParams and location.
Wish this help. You can read the GridLayout.java and ViewGroup.java for more details.
So I solved my issue, although I'm not sure how-
GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
changed to...
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(x,y);
made it work just as I wanted it. But I'm not sure why- If anyone could explain, please do :)

Change height of image button through code in android Studio

I am working in Android studio and using TableLayout. i want to display small imageButtons. and height of each button can be changed programmatically. I tried my best. but does not change the height of imageButton, Please anyone help me, what changes can i make in this code. thanks
public void settable() {
index = 0;
LinearLayout le = (LinearLayout) findViewById(R.id.onofffbutton);
float height = le.getHeight();
height= height/9.0f;
for (int a = 0; a < maxrow; a++) {
TableRow row = new TableRow(this);
for (int b = 0; b < col; b++) {
location[a][b] = new ImageView(this);
/*LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(50, 50);
location[a][b].setLayoutParams(layoutParams);*/
if (isOn[a][b]) {
location[a][b].setBackgroundResource(R.drawable.box1);
} else {
location[a][b].setBackgroundResource(R.drawable.box);
}
location[a][b].setMaxHeight(height);
location[a][b].setOnClickListener(Onclick);
location[a][b].setId(index++);
row.addView(location[a][b]);
}
tableLayout.addView(row, a);
}
}

Setting ImageView' s size by phone screen size

i want ImageView's to look same on different screen sizes. To make it easier for you to understand how it should look there are some image:
Biggest problem is that my imageViews are created programmatically. ImageViews layout and size are set by this code
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = 650;
ImageViewas.getLayoutParams().width = 950;
params.setMargins(0, 50, 0, 0);
Any ideas how to change this code that my app can look same on diffrent screen sizes?
Well, you can retrieve device resolution and set imageView width and height. Here is the solution.
private class ScreenResolution {
int width;
int height;
public ScreenResolution(int width, int height) {
this.width = width;
this.height = height;
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
ScreenResolution deviceDimensions() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// getsize() is available from API 13
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new ScreenResolution(size.x, size.y);
}
else {
Display display = getWindowManager().getDefaultDisplay();
// getWidth() & getHeight() are deprecated
return new ScreenResolution(display.getWidth(), display.getHeight());
}
}
..................
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ScreenResolution screenRes = deviceDimensions();
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = screenRes.height;
ImageViewas.getLayoutParams().width = screenRes.width;
params.setMargins(0, 50, 0, 0);
Also when the device orientation will be changed, the width and height should be swapped. You can do that in onConfigurationChanged:
#Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
// swap device width and height here and re-assign
}

Categories

Resources