Margin's distort image size - java

When I'm setting the margins of this ImageButton, it distorts the size of the image. Why is this happening?
Code:
package com.example.e99900004533.candycollector;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.graphics.Point;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Display;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.LinearLayout;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
public EditText collectedTextEdit;
public ImageButton candyEdit;
public int collected = 0;
public int screenWidth = 300;
public int screenHeight = 300;
Random random = new Random();
public boolean running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collectedTextEdit = (EditText) findViewById(R.id.collectedText);
candyEdit = (ImageButton) findViewById(R.id.candy);
collectedTextEdit.setText("Collected: " + collected);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
addListenerOnButton();
}
public void addListenerOnButton() {
candyEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
collected += 1;
collectedTextEdit.setText("Collected: " + collected);
int candyX = random.nextInt(screenWidth - 50);
int candyY = random.nextInt(screenHeight - 50);
System.out.println(candyX + " : " + candyY);
MarginLayoutParams marginParams = new MarginLayoutParams(candyEdit.getLayoutParams());
marginParams.setMargins(candyX, candyY, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
candyEdit.setLayoutParams(layoutParams);
if (candyX > screenWidth) {
screenWidth -= 50;
layoutParams.setMargins(candyX, candyY, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
candyEdit.setLayoutParams(layoutParams);
}
if (candyY > screenHeight) {
screenHeight -= 50;
layoutParams.setMargins(candyX, candyY, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
candyEdit.setLayoutParams(layoutParams);
}
//while (running == true) {
//candyY -= 1;
//layoutParams.setMargins(candyX, candyY, candyX, candyY);
//candyEdit.setLayoutParams(layoutParams);
//}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the ImageButton code:
<ImageButton
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/candy"
android:background="#drawable/candy"
android:contentDescription="#string/candyImg"
android:clickable="true"
android:layout_below="#+id/collectedText"
android:layout_alignRight="#+id/collectedText"
android:layout_alignEnd="#+id/collectedText" />
Also can anyone explain, or give resources, on how setting margins really works. BTW using Android Api level 15 - 22.
Please Help!

Related

Logic error AndroidStudio

package com.karanvir.tip;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import static com.karanvir.tip.R.drawable.p;
public class MainActivity extends AppCompatActivity {
public EditText people;
public EditText amount;
public EditText percentage;
public EditText finalAmount;
public String finalAmountz;
public RatingBar rating;
public TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
people=(EditText) findViewById(R.id.editText);
amount=(EditText) findViewById(R.id.editText2);
percentage=(EditText) findViewById(R.id.editText3);
finalAmount=(EditText) findViewById(R.id.editText6);
rating=(RatingBar) findViewById(R.id.ratingBar);
//ratingBar.setRating(3);
txt=(TextView) findViewById(R.id.textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void calc(View view){
try{
double pep= Double.parseDouble(people.getText().toString());
double a=Double.parseDouble(amount.getText().toString());
double perc=Double.parseDouble(percentage.getText().toString());
double percc=Double.parseDouble(percentage.getText().toString());
if(pep>1||pep==1){
if(perc>1.0) {
double aa=a;
perc = perc / 100;
a = (a * perc);
double newamount=a+aa;
double placeholder = newamount / pep;
double rounder = Math.round(placeholder);
finalAmountz = "$" + String.valueOf(rounder);
finalAmount.setText(finalAmountz.toString());
if (perc>0.12) {
rating.setRating(5);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
else if (perc>0.10&&perc<0.12||perc==0.10) {
rating.setRating(4);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
else if (perc>0.7&&perc<0.10||perc==0.07) {
rating.setRating(3);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
else if (perc>0.05&&perc<0.07||perc==0.05) {
rating.setRating(2);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
if (perc<0.05) {
rating.setRating(1);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
}
}
else if (pep<1||pep==1){
Toast.makeText(MainActivity.this, "Please Enter 1 person minimum", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Please don't rip me apart here. But I'm new to android development. I'm making a tip calculator app right now, everything works the way I want it to. However, my star Calculation is off. it keeps showing 1 star? Please look at lines 72-117. Can someone help me? Sorry for the noob question, I'm still learning.
package com.karanvir.tip;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import static com.karanvir.tip.R.drawable.p;
public class MainActivity extends AppCompatActivity {
public EditText people;
public EditText amount;
public EditText percentage;
public EditText finalAmount;
public String finalAmountz;
public RatingBar rating;
public TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
people=(EditText) findViewById(R.id.editText);
amount=(EditText) findViewById(R.id.editText2);
percentage=(EditText) findViewById(R.id.editText3);
finalAmount=(EditText) findViewById(R.id.editText6);
rating=(RatingBar) findViewById(R.id.ratingBar);
//ratingBar.setRating(3);
txt=(TextView) findViewById(R.id.textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void calc(View view){
try{
double pep= Double.parseDouble(people.getText().toString());
double a=Double.parseDouble(amount.getText().toString());
double perc=Double.parseDouble(percentage.getText().toString());
if(pep>1||pep==1){
if(perc>1.0) {
double aa=a;
perc = perc / 100;
a = (a * perc);
double newamount=a+aa;
double placeholder = newamount / pep;
double rounder = Math.round(placeholder);
finalAmountz = "$" + String.valueOf(rounder);
finalAmount.setText(finalAmountz.toString());
if (perc>12) {
rating.setRating(5);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
if (perc>10&&perc<12||perc==10) {
rating.setRating(4);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
if (perc>7&&perc<10||perc==7) {
rating.setRating(3);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
if (perc>5&&perc<7||perc==5) {
rating.setRating(2);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
if (perc<5) {
rating.setRating(1);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
}
else if(perc<=1.0){
double aa=a;
a = (a * perc);
double newamount=a+aa;
double placeholder = newamount / pep;
double rounder = Math.round(placeholder);
finalAmountz = "$" + String.valueOf(rounder);
finalAmount.setText(finalAmountz.toString());
finalAmountz = "$" + String.valueOf(rounder);
finalAmount.setText(finalAmountz.toString());
if (perc>12)
rating.setRating(5);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
if (perc>10&&perc<12||perc==10)
rating.setRating(4);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
if (perc>7&&perc<10||perc==7)
rating.setRating(3);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
if (perc>5&&perc<7||perc==5)
rating.setRating(2);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
if (perc<5)
rating.setRating(1);
rating.setVisibility(View.VISIBLE);
txt.setVisibility(View.VISIBLE);
}
}
else if (pep>1){
Toast.makeText(MainActivity.this, "Please Enter 1 person minamum", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
You are dividing perc by 100
if(pep>1||pep==1){
if(perc>1.0) {
double aa=a;
perc = perc / 100;
....
Unless the value you input is superior to 500 then its value will always be inferior to 5 (your last condition) and therefore always give 1 star

Android Studio unable to resolve method in class

I am trying to make a basic connect 3 app as part of a course challenge.
The problem I am having is that I am unable to access the methods inside the class Players in order to set which buttons have been pressed by which players: Cannot resolve method 'noughtsPlayer'.
I created an instance of Players on the onCreate method and declared it at the top of the script. That instance itself is recognised but for some reason the contained methods, noughtsPlayer and crossesPlayer are not.
MainActivity.java
package com.example.richardcurteis.connect3;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public boolean noughtsTurn;
ArrayList board;
String players;
public void receiveClick(View view) {
String buttonPressed = (String) view.getTag();
board.remove(buttonPressed);
if (view instanceof Button) {
Button B = (Button) view;
B.setText(noughtsTurn ? players.noughtsPlayer() : players.crossesPlayer());
}
}
class Players {
public String noughtsPlayer() { return "O"; }
public String crossesPlayer() { return "X"; }
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
boolean noughtsTurn = true;
board = new ArrayList();
for (int x = 0; x < getBoardSize(); x++) {
String y = String.valueOf(x);
board.add(y);
}
Players players = new Players();
}
public int getBoardSize() {
int buttonCount = 0;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
View tableLayoutChild = tableLayout.getChildAt(rowIndex);
if (tableLayoutChild instanceof TableRow) {
for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
if (view instanceof Button) {
buttonCount++;
}
}
}
}
return buttonCount;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You have global variable String players and local variable Players players.
This is problem.
And class String doesn't have those methods.
To solve this problem change String players; to Players players;
and Players players = new Players(); to players = new Players();

How to swap the position of two buttons in android?

I am creating a a puzzle match game where in order to match two buttons together you must swap the position of them. for example, i want to swap the position of button1 with the position that button2 is in. Anybody have any suggestions?
Here is my code below:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class puzzle extends ActionBarActivity {
private TextView moveCounter;
private TextView feedbackText;
private Button[] buttons;
private Boolean bad_move=false;
// private static final Integer[] goal = new Integer[] {0,1,2,3,4,5,6,7,8};
// private String [][] puz = new String [3][3];
Button b [][];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
swap();
}
private void setBoard(){
b = new Button[3][3];
b[0][0]= (Button).findViewById(R.id.button1);
b[0][1]= (Button).findViewById(R.id.button2);
b[0][2] = (Button).FindById(R.id.button3);
b[1][0] = (Button).FindBdyId(R.id.button4);
b[1][1] = (Button).FindById(R.id.button5);
b[1][2] = (Button).FindById(R.id.button6);
b[2][0] = (Button).FindById(R.id.button7);
b[2][1] = (Button).FindById(R.id.button8);
b[2][2] = (Button).FindById(R.id.button9);
}
private void swap() {
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_puzzle, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are using API level greater than 11, you can use getX() and getY() to get coordinates of a button.
And setX() and setY() to set a button in a particular coordinate.
for example,
// getting coordinates of button
float posX = button.getX();
float posY = button.getY();
// setting button2 in the coordinates that we got above
button2.setX(posX);
button2.setY(posY);
The way I've gotten this work is similar to your approach you had originally posted. Try giving this a shot:
Button btnOne = (Button) findViewById(R.id.buttonOne);
Button btnTwo = (Button) findViewById(R.id.buttonTwo);
float posOneX = btnOne.getX();
float posOneY = btnOne.getY();
float posTwoX = btnTwo.getX();
float posTwoY = btnTwo.getY();
btnOne.setX(posTwoX);
btnOne.setY(posTwoY);
btnTwo.setX(posOneX);
btnTwo.setY(posOneY);

Random button Android project

I want to make an app that when you click a button it will go to a random place on the screen. I want it to be an ImageButton the when onClick well go to a random place on the screen. I've attempted before. But to no success. Here is some of the code I've already attempted with. --->
package com.example.e99900004533.candycollector;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.graphics.Point;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Display;
import android.view.ViewGroup.MarginLayoutParams;
import android.animation.ObjectAnimator;
import android.widget.RelativeLayout;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
public EditText collectedTextEdit;
public ImageButton candyEdit;
public int collected = 0;
public int screenWidth = 300;
public int screenHeight = 300;
Random random = new Random();
public boolean running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collectedTextEdit = (EditText) findViewById(R.id.collectedText);
candyEdit = (ImageButton) findViewById(R.id.candy);
collectedTextEdit.setText("Collected: " + collected);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
addListenerOnButton();
}
public void addListenerOnButton() {
candyEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
collected += 1;
collectedTextEdit.setText("Collected: " + collected);
int candyX = random.nextInt(screenWidth - 50);
int candyY = random.nextInt(screenHeight - 50);
System.out.println(candyX + " : " + candyY);
MarginLayoutParams marginParams = new MarginLayoutParams(candyEdit.getLayoutParams());
marginParams.setMargins(candyX, candyY, 0, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
candyEdit.setLayoutParams(layoutParams);
//if (candyX > screenWidth) {
//screenWidth -= 50;
//layoutParams.setMargins(candyX, candyY, candyX, LayoutParams.WRAP_CONTENT);
//candyEdit.setLayoutParams(layoutParams);
//}
//if (candyY > screenHeight) {
//screenHeight -= 50;
//layoutParams.setMargins(candyX, candyY, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//candyEdit.setLayoutParams(layoutParams);
//}
//while (running == true) {
//candyY -= 1;
//layoutParams.setMargins(candyX, candyY, candyX, candyY);
//candyEdit.setLayoutParams(layoutParams);
//}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I hope you are using Android Studio as it gives you a beautiful way of accessing all the benefits of the Android API.
Anyway, before I post the code, you set the onClickListener within your java code and while that is fine, it can clutter up your code. A much more aesthetically pleasing solution is to use XML and a button's android:onClick. You will see this in the code.
Java:
package testinc.com.randombutton;
import android.graphics.Point;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends ActionBarActivity {
// Encapsulating the data just to be safe...
private int collected = 0;
private int screenWidth = 300;
private int screenHeight = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
TextView collectedView = (TextView) findViewById(R.id.collectedTV);
collectedView.setText("Collected: " + collected);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void toRandomPosition(View view) {
// Based on our collection candy collection:
collected += 1;
TextView collectedView = (TextView) findViewById(R.id.collectedTV);
collectedView.setText("Collected: " + collected);
// Based on position of our candy:
Random random = new Random();
// Understand nextInt(N) will go from 0 -> N-1, also are you trying to control where it can go?
float candyX = (float) random.nextInt(screenWidth - 50);
float candyY = (float) random.nextInt(screenHeight - 50);
// I didn't write it, but you need to check these float values if they exceed the screen width and the screen length. */
// Sout to check coordinates
System.out.println(candyX + " : " + candyY);
// To change margins:
ImageButton imgButton = (ImageButton) findViewById(R.id.changePlace);
imgButton.setX(candyX);
imgButton.setY(candyY);
}
}
Android:
Note: I used a linear layout because I dislike the relative. You can change it without repercussions I suppose.
<LinearLayout 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:id="#+id/collectedTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton android:id="#+id/changePlace"
android:onClick="toRandomPosition"
android:contentDescription="It's a button, ha za"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Key parts:
android:onClick="toRandomPosition" hooks up with the method, public void toRandomPosition(View view)
setX and setY require floating point numbers to set the position. Unfortunately, it seems that the random class does not have nextFloat(float n) in its class. I recommend just casting the int as a float for now.
Seeing that I am doing this now, here is a possible (I have not checked it) solution to the coordinates going beyond the bounds of the screen:
while ( candyX >= screenWidth || candyY >= screenHeight) {
candyX = (float) random.nextInt(screenWidth - 50);
candyY = (float) random.nextInt(screenHeight - 50);
}
I checked if the position was equal because a button at the corner of the screen is a pain to find and may be skewed off the display.

How do I change the font for tab titles created from PagerSlidingTabStrip?

Here is the library in question: https://github.com/astuetz/PagerSlidingTabStrip
I figure it has something to do with .setTypeface() but I have no idea how to use it. I put the font I want in the assets folder. Here's my code.
Start.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
public class Start extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private int currentColor = 0xFF547CC1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
tabs.setIndicatorColor(currentColor);
/*Typeface tf = Typeface.createFromAsset(getAssets(), "RobotoCondensed-Regular.ttf");
tabs.setTypeface(tf,Typeface.NORMAL);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}else if(id == R.id.add_location){
Toast.makeText(getApplicationContext(), "todo", Toast.LENGTH_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter a location");
alert.setMessage("Enter a zipcode or city");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Editable value = input.getText();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Canceled.
}
});
alert.show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter{
private final String[] TABS = {"Today", "This Week"};
public MyPagerAdapter(FragmentManager fm){
super(fm);
}
public CharSequence getPageTitle(int position){
return TABS[position];
}
#Override
public int getCount() {
return TABS.length;
}
#Override
public Fragment getItem(int position) {
return WeatherTabs.newInstance(position);
}
}
}
activity_start.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
app:pstsShouldExpand="true" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".Start" />
</RelativeLayout>
As you can see in Start.java, I have already tried to use .setTypeface() in the onCreate() method and it produces no errors, but when I run my app it crashes on startup so I'm not using .setTypeface() correctly.
add below code in your activity it works:
com.viewpagerindicator.TabPageIndicator indicator = (com.viewpagerindicator.TabPageIndicator) findViewById(R.id.tabs);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/BYekan+ Bold.ttf");
LinearLayout view = (LinearLayout) indicator.getChildAt(0);
int tabCount=3;
for(int i=0;i<tabCount;i++){
TextView textView = (TextView) view.getChildAt(i);
textView.setTypeface(type);
}
if you use this library :
https://github.com/jpardogo/PagerSlidingTabStrip
in PagerSlidingTabStrip class change line 185 :
mTabTextTypeface = Typeface.create(tabTextTypefaceName, mTabTextTypefaceStyle);
to this :
mTabTextTypeface = Typeface.create(Typeface.createFromAsset(context.getAssets(),"DroidNaskh.ttf"), mTabTextTypefaceStyle);
I ran into this a while back - without overriding ViewPager code there isn't a way to do this
I used PagerSlidingTabStrip lib and i set like this and it is worked for me
public void changeTabsFont( PagerSlidingTabStrip tabs)
{
try
{
Typeface tab_face;
tab_face = Typeface.create(Typeface.createFromAsset(activity.getAssets(), "font/NanumBarunGothic.ttf"), Typeface.NORMAL);
ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++)
{
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++)
{
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView)
{
((TextView) tabViewChild).setTypeface(tab_face, Typeface.NORMAL);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

Categories