Android: add textview in a RelativeLayout in random position - android

I'm adding some textview in a RelativeLayout called "number_container", this is my code but i don't see nothing, the textviews are not added...
private void labelAnimation(){
TextView number = new TextView(getApplicationContext());
number.setGravity(Gravity.CENTER);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Gang of Three.ttf");
number.setTypeface(font);
Random random = new Random();
int random_size = random.nextInt(170 - 30) + 30;
number.setTextSize(random_size);
number.setTextColor(000000);
int random_text = random.nextInt(10-1)+1;
number.setText(Integer.toString(random_text));
int random_width = random.nextInt(width_screen - 50) + 50;
int random_height = random.nextInt(height_screen - 50) + 50;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(random_width, random_height, 0, 0);
number.setLayoutParams(lp);
number_container.addView(number);
int random_delay = random.nextInt(800-100)+100;
final Handler animation_sun = new Handler();
animation_sun.postDelayed(new Runnable() {
#Override
public void run() {
labelAnimation();
}
}, random_delay);
}
I tried also to remove the custom font but no good results.
What can I do?

My problem was the color of the textView...
number.setTextColor(color.WHITE);

Related

please tell me how to set textview background color when textview id is dynamic

I want to change background color of particular textview. Need different background for each textview. I write this code, textview make but this give error
"textview.findViewById().setBackgroundColor(Color.RED);"
Textview textview;
for (int i = 0; i < 3; i++) {
textview = new TextView(this);
textview .setId(i);
textview .setTextSize(15);
textview .setTextColor(Color.BLACK);
}
textview.findViewById(1).setBackgroundColor(Color.RED);
self Solution
Use Linear layout and add
textview
then change
LinearLayout linear_layout;
Textview textview;
for (int i = 0; i < 3; i++) {
textview = new TextView(this);
textview .setId(i);
textview .setTextSize(15);
textview .setTextColor(Color.BLACK);
linear_layout.add(textview);
}
linear_layout.findViewById(1).setBackgroundColor(Color.RED);
Use this code
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);
Random rand = new Random();
for (int i = 0; i < 3; i++) {
int r = rand.nextInt(255);
int g = rand.nextInt(255);
int b = rand.nextInt(255);
int randomColor = Color.rgb(r,g,b);
Textview textview = new TextView(this);
textview.setId(i);
textview.setTextSize(15);
textview.setTextColor(Color.BLACK);
textview.setBackgroundColor(randomColor);
linearLayout.addView(textview);
}
Try this:
List<TextView> textViewList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
TextView textview = new TextView(this);
textview.setTextSize(15);
textview.setTextColor(Color.BLACK);
textViewList.add(textview);
}
int index = 2;
textViewList.get(index).setBackgroundColor(Color.RED);
Use txtCompanyName.setBackgroundResource(R.color.white);
or
Below is snippet might help you where txtChannelName is an object of TextView
txtCompanyName.setBackgroundColor(Color.RED);
or
txtCompanyName.setBackgroundColor(Color.parseColor("#ffffff"));
Hope it will help you
Create List of type TextView and add your textview like below
List<TextView> textViewList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
TextView textview = new TextView(this);
textview.setTextSize(15);
textview.setTextColor(Color.BLACK);
textViewList.add(textview);
}
Then on button click pass your value to change the text background color like below
private void changeBackGroundColor(int index) {
textViewList.get(index).setBackgroundColor(Color.RED);
}
This will change your respective text view bacground color
Use getRandomColor method
public int getRandomColor(){
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
textViewList.get(index).setBackgroundColor(getRandomColor());
Best Solution
To Genrate Light colors use this -
public int generateRandomLightColor() {
// This is the base color which will be mixed with the generated one
final int baseColor = Color.WHITE;
final int baseRed = Color.red(baseColor);
final int baseGreen = Color.green(baseColor);
final int baseBlue = Color.blue(baseColor);
final int red = (baseRed + mRandom.nextInt(256)) / 2;
final int green = (baseGreen + mRandom.nextInt(256)) / 2;
final int blue = (baseBlue + mRandom.nextInt(256)) / 2;
return Color.rgb(red, green, blue);
}
It show color like - https://stackoverflow.com/a/43235/4741746
To genrate Dark Color use this -
public int getRandomDarkColor(){
Random rnd = new Random();
//use rnd.nextInt(0x1000000) & 0x7F7F7F
return Color.argb(255, rnd.nextInt(0x1000000), rnd.nextInt(0x1000000), rnd.nextInt(0x1000000));
}

Get layout width and set new width value in onGlobalLayoutListener

I create programmatically few layouts and I need get width one of them, recalculate this value and change. All this action I do in onGlobalLayoutListener. But when I set a new width value, he doesnt change.
private RelativeLayout batteryContainer;
private LinearLayout batteryLeftSide;
private LinearLayout batteryRightSide;
public void drawBattery(){
handler.post(new Runnable() {
#Override
public void run() {
//Контейнер всієї батарейки
batteryContainer = new RelativeLayout(activity);
RelativeLayout.LayoutParams batteryContainerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
batteryContainerParams.setMargins((int) convertDpToPixel(containerMarginLeft), (int) convertDpToPixel(containerMarginTop), (int) convertDpToPixel(containerMarginRight), (int) convertDpToPixel(containerMarginBottom));
if(layoutBelow != null){
batteryContainerParams.addRule(RelativeLayout.BELOW, layoutBelow.getId());
}
if(layoutAbove != null){
batteryContainerParams.addRule(RelativeLayout.ABOVE, layoutAbove.getId());
}
batteryContainer.setLayoutParams(batteryContainerParams);
batteryContainer.setBackgroundColor(Color.parseColor("#505050"));
batteryContainer.setId(containerId);
int leftWidth = 0;
int rightWidth = 0;
//Ліва частина батарейки
batteryLeftSide = new LinearLayout(activity);
batteryLeftSide.setOrientation(LinearLayout.HORIZONTAL);
RelativeLayout.LayoutParams batteryLeftSideParams = new RelativeLayout.LayoutParams((int)convertDpToPixel(leftWidth), (int)convertDpToPixel(sideHeight));
batteryLeftSideParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
batteryLeftSide.setLayoutParams(batteryLeftSideParams);
batteryLeftSide.setBackgroundColor(Color.parseColor("#900000"));
batteryLeftSide.setId(leftSideId);
//Права частина батарейки
batteryRightSide = new LinearLayout(activity);
batteryRightSide.setOrientation(LinearLayout.HORIZONTAL);
RelativeLayout.LayoutParams batteryRightSideParams = new RelativeLayout.LayoutParams((int)convertDpToPixel(rightWidth), (int)convertDpToPixel(sideHeight));
batteryRightSideParams.addRule(RelativeLayout.RIGHT_OF, batteryLeftSide.getId());
batteryRightSide.setLayoutParams(batteryRightSideParams);
batteryRightSide.setBackgroundColor(Color.parseColor("#009900"));
batteryRightSide.setId(rightSideId);
//Додамо праві та ліві сторони в контейнер
batteryContainer.addView(batteryLeftSide);
batteryContainer.addView(batteryRightSide);
//Додамо контейнер в кореневий Layout на активності
rootLayout.addView(batteryContainer);
//Обчислення яка сторона батарейки займе 50%
ViewTreeObserver observer = rootLayout.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int batteryContainerWidth = batteryContainer.getMeasuredWidth();
int halfPlace = batteryContainerWidth * 50 / 100;
trustFromMe = halfPlace;
if(trustToMe > trustFromMe){
batteryLeftSide.getLayoutParams().width = halfPlace;
}
if(trustToMe < trustFromMe){
batteryRightSide.getLayoutParams().width = halfPlace;
}
if(trustToMe == trustFromMe){
batteryLeftSide.getLayoutParams().width = halfPlace;
batteryRightSide.getLayoutParams().width = halfPlace;
}
}
});
//but width not change
}
});
}
Try adding this to the end of the GlobalLayoutListener:
rootLayout.requestLayout();
This should force the layout to redraw it's size. If this doesn't work you may want to try creating and setting new LayoutParams as well.

I want to display the image view at different position on the screen randomly

Here the ImageView is displaying only at one position, after closing the activity the next time the activity is opened the ImageView will be on another position... I want to display the ImageView randomly at diff position on the same activity itself. The image view should appear on one point suddenly the next second ImageView should disappear from that position and appear on the next position. How can i do it?
public class page2 extends ActionBarActivity {
ImageView b2;
int count = 0;
Handler handler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
Intent c = getIntent();
String name = c.getStringExtra("t");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
b2 = (ImageView) findViewById(R.id.redball);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)b2.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
absParams.x = r.nextInt(width ) ;
absParams.y = r.nextInt(height );
b2.setLayoutParams(absParams);
Animation animation = AnimationUtils.loadAnimation(page2.this, R.anim.fade);
// Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.activity_move);
b2.startAnimation(animation);
// b2.startAnimation(animation1);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = count + 1;
}
});
handler = new Handler();
final Runnable t = new Runnable() {
public void run() {
Intent d = new Intent(getApplicationContext(), Page3.class);
d.putExtra("count", count);
d.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(d);
}
};
handler.postDelayed(t, 4000);
}
#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_page2, menu);
return true;
}
Don't use AbsoluteLayout, Why not use a custom view draw it?
You can achieve this by using Imageview within FrameLayout. Just change the layoutParams of the image to change its position.
As I understand it, you want that each time the activity is opened, so f you dont want to actually view to the user that the ImageView moves, why are you using Animation? You may just dynamically add the ImageView to the activity each time, and each time assign it different Margin attributes.
LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
ImageView iv = new ImageView(getActivity());
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.yourimage);
layout.addView(iv);
for calucation
ContainerHeight = blinkerContainer.getHeight(); // total height of screen
ContainerWidth = blinkerContainer.getWidth(); //total width
blinkerHeight = blinkView.getHeight();
blinkerWidth = blinkView.getWidth();
minTopMargin = 30;
minLeftMargin = 30;
maxTopMargin = ContainerHeight - blinkerHeight - 30;
maxLeftMargin = ContainerWidth - blinkerWidth - 30;
for positioning
LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) blinkView
.getLayoutParams();
params.leftMargin = minLeftMargin
+ new Random().nextInt(maxLeftMargin - minLeftMargin);
params.topMargin = minTopMargin
+ new Random().nextInt(maxTopMargin - minTopMargin);
and you can use AlaramManager for Scheduling
Your solution is almost correct. Unfortunately, it looks like you're restarting the activity from your timer. Instead, you should just trigger the redraw.
This question has a couple of solutions on how to create a recurring timer. The solution with runOnUiThread() should allow you to execute the randomisation and re-displaying of the ImageView.

Android get programmatically created view's width

I have TextView created programmatically, like that:
TextView mTextView = new TextView(getApplicationContext());
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
mTextView.setText(mText);
mTextView.setLayoutParams(params);
mTextView.setPadding(2, 2, 2, 2);
mTextView.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(mTextView);
textViewsWidth = mTextView.getWidth();
But mTextView.getWidth() always returns 0
And if I try:
mTextView.getLayoutParams().width
It returns the LayoutParams corresponding value in the LayoutParams class (-1 or -2)
How can I get the view's width ?
EDIT I need to do this here:
#Override
public void onPostExecute(Hashtable<String, Integer> hash){
final ScrollView tagMapScroll = (ScrollView) findViewById(R.id.tagMapScroll);
final LinearLayout tagMap = (LinearLayout) findViewById(R.id.tagMap);
final ArrayList<Integer> arr = new ArrayList<Integer>(hash.values());
final Enumeration<String> e = hash.keys();
int index = 0;
int textViewsWidth = 0;
while(e.hasMoreElements()){
final TextView tV = new TextView(getApplicationContext());
tV.setTextColor(Color.parseColor("#666666"));
tV.setText(Html.fromHtml(randomColor() + e.nextElement()));
tV.setTextSize(arr.get(index));
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
tV.setLayoutParams(params);
tV.setPadding(2, 2, 2, 2);
tV.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(tV);
textViewsWidth += tV.getWidth();
index++;
}
tagMapScroll.setVisibility(ScrollView.VISIBLE);
}
EDIT SOLUTION I used this from #androiduser's answer:
mTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();
Problem solved !
I used this solution:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Ensure you call it only once
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Here you can get the size :)
}
});
get this way:
tV.post(new Runnable() {
#Override
public void run() {
int width=tV.getMeasuredWidth();
}
});
those values are constant value for FILL_PARENT and WRAP_CONTENT. If you want to check the view size you can try this way:
tagMap.addView(mTextView);
tagMap.post(new Runnable() {
#Override
public void run() {
mTextView. getWidth();
}
});
you have to wait until android draws the TextView. This way you are posting a Runnable in the tagMap queue, that is executed, hopefully after the textview is draw (so it should be weight and height)
In this method you can get the width height of the view..
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
int width = mTextView.getWidth();
int height = mTextView.getHeight();
}
and define TextView mTextView as global
You have to use ViewTreeObserver class which is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.
In the Activity's onCreate mehotd put this:
ViewTreeObserver vto = mTextView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int viewWidth = mTextView.getMeasuredWidth();
}
});

moving views positions refresh

First of all sorry for my English. I just began development with android
My problem is:
I create an ImageView in a random position, every time you touch the image, it change its position. When you touch you have a probability (%) that appears another Image in another random position. But my problem is when the second image appear, the first one come back to its "created position" and not keeping position.
The "Bomb" is created well, but then the first image back to created position and not the position it is in the moment.
Thanks all for the help
Example of my test code:
public void start(View view) {
width= 60;
height= 60;
layout = (RelativeLayout) findViewById(R.id.rellayout);
widthLayout = layout.getWidth();
heightLayout = layout.getHeight();
r = new Random();
x = r.nextInt(widthLayout - 60);
y = r.nextInt(heightLayout - 60);
imagen = new ImageView(this);
imagen.setImageResource(R.drawable.led_circle_green);
RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
60, 60);
paramss.leftMargin = x;
paramss.topMargin = y;
imagen.setAdjustViewBounds(true);
layout.addView(imagen, paramss);
Animation aparecer = AnimationUtils
.loadAnimation(this, R.anim.aparecer);
imagen.startAnimation(aparecer);
imagen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
push();
}
});
public void push() {
createBomb();
move();
}
public void createBomb() {
r = new Random();
int proba = r.nextInt(100);
if (proba < 50) {
x = r.nextInt(widthLayout - 60);
y = r.nextInt(heightLayout - 60);
bomb = new ImageView(this);
bomb.setImageResource(R.drawable.bomb);
RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
60, 60);
paramss.leftMargin = x;
paramss.topMargin = y;
bomb.setAdjustViewBounds(true);
layout.addView(bomb, paramss);
}
}
public void move() {
r = new Random();
int proba = r.nextInt(100);
if (proba < 10) {
ximg = r.nextInt(widthLayout - width);
yimg = r.nextInt(heightLayout - height);
imagen.layout(ximg, yimg, ximg + width, yimg + height);
}
}
layout method does not applies persistent changes to a view state. Set new layout params to image view, which will specify it's new position (do not use layout method).
When you add new ImageView2 RelativeLayout decides to relayout its childs and resets ImageView1 position.
Read this.

Categories

Resources