I need to set background of the TextView without stretching like this:
I tried draw9patch but seems that it doesn't do that work. How can I reach this efect? I could also use ImageView, but I don't know how I can add text in ImageView (I cannot use layout or two views... image and text need to be in one view)
i think you should use drawableLeft
something like this :
<EditText
android:id="#+id/question_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint=" your question"
android:drawableLeft="#drawable/ic_menu_info_details"
android:layout_weight="1"
android:singleLine="true" />
You can do it using a button and dont set any click listeners for it..:
Here is the code:
Button btnIconTxt=new Button(context);
btnIconTxt.setId(id);
//this aligns a image to the left of ur text view(This the important line).
btnIconTxt.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(context.getResources(),bitmapOfYourImage), null, null, null);
btnIconTxt.setText(message);
btnIconTxt.setTextSize(TypedValue.COMPLEX_UNIT_PX, sizeInPx);
btnIconTxt.setWidth(widthInPx);
btnIconTxt.setTextColor(Color.RED);
int currentApi = Build.VERSION.SDK_INT;
if(currentApi >= 16)
btnIconTxt.setBackground(btnColor);
else
btnIconTxt.setBackgroundDrawable(btnColor);
RelativeLayout.LayoutParams SDISP_params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
btnIconTxt.setLayoutParams(params1);
//U can set the x and y margin for this button using
//params1.leftMargin = xPixels;
// params1.topMargin = yPixels;
yourParentLayout.addView(btnIconTxt);
Related
I have a RelativeLayout called current_layout which I place my views on. When I attempt to addView(TextView) , nothing is displayed. However when adding an ImageView, it works just fine. Why is my TextView not displaying?
public static void draw_shard(int x, int y, int amount_collected){//X and Y are GAMESURFACE values. Needs to increment by gamesurface y.
ImageView shard = create_iv(); // Creates a new instance of an ImageView (parameter is the context of MainActivity)
shard.setBackgroundDrawable(shard_icon);
shard.setX(x);
shard.setY(y+ImageLoader.get_score_bar_height());
TextView tv = new TextView(MainActivity.current_context);
tv.setX(shard.getX() + shard.getWidth());
tv.setY(shard.getY());
tv.setTypeface(Variables.joystix);
tv.setTextSize(shard.getHeight());
tv.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
tv.setText("+" + amount_collected);
tv.setTextColor(Color.WHITE);
current_layout.addView(shard);
current_layout.addView(tv);
}
I am adding the TextView on top of a black background also.
The problem was with shard.getWidth() and shard.getHeight() , which were returning 0.
An alternate and easy way to do that is:
Add the TextView in the layout file and set its visibility to gone, and when you need to show the TextView, just change the visibility of that TextView.
Sample code for XML file:
<TextView
android:id="#+id/textview"
android:layout_height="wrap_content"
android:layout-width="wrap_content"
android:visibility="gone">
<!-- Add other attributes too -->
And when you need that TextView, add this line of code:
findViewById("textview").setVisibility(View.VISIBLE);
findViewById("textview").setText("" + amount_collected);
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product");
ll.addView(product);
Please try it.
But why are you adding TextView using java code?
You can easily do it in XML.
<TextView
android:layout_width="wrap_content"
android:id="#+id/textView"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#color/colorPrimary"
android:textColor="#color/colorPrimary" />
It will help you to understand
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText("Your Text that you want to add");
linearLayout.addView(textView);
Thanks
I'm having an issue working with layouts, I've a linear layout (could be a relative layout or a table layout) which will contain an undefined number of buttons when the activity is loaded. This means, the quantity of buttons will be determined when the activity is being created. The thing is, I'm trying to fit them all in one line (with a center gravity) without changing each buttons' width UNTIL one of them reaches the margin of the screen. In other words, I want the buttons JUST to resize when at least one of them reaches the margin of the screen. That is because, I can't determine the space they're going to use because they are not created.
My actual linear layout:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="#+id/linearLayout_1"
android:layout_above="#+id/linearLayout_2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="30dp"
android:orientation="horizontal"
android:gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</LinearLayout>
Piece of code that creates the buttons:
protected void hacerVisiblesRespuesta(){
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayout);
assert linearLayout != null;
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,40, getResources().getDisplayMetrics());
for(int i = 0; i < longuitudPalabra; i++){
String boton = "btn_rsp" + Integer.toString(i+1);
Button bt = new Button(this);
bt.setText("");
bt.setId(getResourceId(boton,"id",getPackageName()));
bt.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT
, height
, 1.0f));
bt.setTextColor(Color.BLACK);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickBotonRespuesta(v);
}
});
bt.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
bt.setBackground(getDrawable(R.drawable.bgbtnrsp));
}else{
//bt.setBackgroundDrawable(getDrawable(R.drawable.bgbtnrsp));
}
bt.setTextSize(20);
Typeface typeFace= Typeface.createFromAsset(getAssets(),"fonts/Montserrat-Regular.ttf");
bt.setTypeface(typeFace);
linearLayout.addView(bt);
}
}
I've tried many things, one of them was to make the buttons' width variable with weight property. The thing is if there are a small quantity of buttons, lets say 4, their width ended up enormous. Is there any way to achieve this through code? Thanks.
have you tried this?
button.setLayoutParams (new LayoutParams(50, LayoutParams.WRAP_CONTENT)
Ok... here's my situation.
I have a carousel of images in a HorizontalScrollView - which contains a LinearLayout - in my Activity, like so:
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/slider"
android:scrollbars="none" >
<LinearLayout
android:id="#+id/carousel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
</HorizontalScrollView>
I have a TypedArray, loop through it, and on each run, set these images programatically, add a ClickListener and a Tag, and add this ImageView to the LinearLayout (set in my Activity Layout), like so:
// Get the array
final TypedArray carouselArray = getResources().obtainTypedArray(R.array.carousel_array);
// Populate the Carousel with item
for (int i = 0 ; i < carouselArray.length() ; ++i) {
// Image Item
ImageView outerImage;
// Set the image view resource
if(i == 0) {
outerImage.setImageResource(R.drawable.toy_filter_clear);
}
else {
outerImage.setImageResource(carouselArray.getResourceId(i, -1));
}
// Set Touch Listener
outerImage.setOnTouchListener(this);
final String prepend = "CAROUSEL_";
final String index = String.valueOf(i);
final String tag = prepend.concat(index);
outerImage.setTag(tag);
/// Add image view to the Carousel container
mCarouselContainer.addView(outerImage);
}
But now, I just found out that I have to programatically add a second image to sit inside/on top of the first image at particular coordinates (damn you UI ppl!). I need these to be considered the same image/view essentially, so need to pack them together inside of a layout, I am assuming. So I have made a layout file, like so:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/carousel_item"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/carousel_outer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/toy_filter_normal"
/>
<ImageView
android:id="#+id/carousel_inner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/carousel_outer"
android:layout_alignRight="#+id/carousel_outer"
android:layout_marginBottom="10dp"
android:layout_marginRight="5dp"
android:src="#drawable/thumb_nofilter"
/>
</RelativeLayout>
This has the proper positioning, and the default images set on it. So what I want to be able to do is to reach into the Layout file, grab the ImageViews by their ID, overwrite the image if necessary, and then add that RelativeLayout to my LinearLayout at the end of my loop... sounds easy enough, right ?
My first attempt was to do it like this :
RelativeLayout item = (RelativeLayout) findViewById(R.id.carousel_item);
ImageView outerImage = (ImageView) item.findViewById(R.id.carousel_outer);
ImageView innerImage = (ImageView) item.findViewById(R.id.carousel_inner);
... but that gives me a NullPointer on the ImageView...So then I tried to inflate the RelativeLayout first, like this:
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.carousel_item_layout, null);
ImageView outerImage = (ImageView) view.findViewById(R.id.carousel_outer);
ImageView innerImage = (ImageView) view.findViewById(R.id.carousel_inner);
This gets rid of the NPE's, and (apparently) let's the images be set properly like so:
if(i == 0) {
outerImage.setImageResource(R.drawable.toy_filter_clear);
innerImage.setImageResource(0);
}
else {
outerImage.setImageResource(R.drawable.toy_filter_normal);
innerImage.setImageResource(carouselArray.getResourceId(i, -1));
}
but when I try to add the outerImage ImageView back to the LinearLayout, I get an NPE there:
mCarouselContainer.addView(outerImage);
More to the point, I don't want to add ONLY the one ImageView to the LinearLayout/HorizontalScrollView - I want to somehow pack the resulting images back into the RelativeLayout and add the whole thing back into my LinearLayout... but, it is worth mentioning, that this also gives me an NPE.
What is a guy to do ? Any thoughts appreciated...
Ok... Wow, thanks SO Code Monkey!
I managed to fix this with a one line fix, by adding the inflated View to the LinearLayout instead of the ImageView or the RelativeLayout (which wasn't doing anything), like so:
mCarouselContainer.addView(view);
Don't know why I hadn't tried that before, but I was unclear on whether as it's children were being updated if it would reflect the parent, so to speak... now I know it was.
I'm gonna keep the question up, as I think it's helpful... ?
I'm having a difficulty adding buttons dynamically to a ScrollView. The code below is adding the buttons BUT there is no scroller.
If I'm putting the buttons directly in the XML (not dynamically) it's working and I can scroll down/up.
My view:
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="264dp"
android:layout_height="match_parent"
android:fillViewport="true"
>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="264dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
>
** HERE THE BUTTONS SHOULD BE ADDED DYNAMICALLY **
</LinearLayout>
</ScrollView>
The code which adding buttons:
// create new button
final Button newbutton = new Button(this);
// set background color
newbutton.setBackgroundColor(Color.GRAY);
// set width and height
newbutton.setWidth(50);
newbutton.setHeight(20);
// set position
newbutton.setY(((float)numOfButton*20)+20);
newbutton.setX(100);
// set text
newbutton.setText(Integer.toString(numOfButton));
// create patameter
final LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
//set listener
android.view.View.OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// make all the DrawView invisible
for(View view : comments){
view.setVisibility(View.INVISIBLE);
}
// set the chosen comment visible
comments.get(numOfButton).setVisibility(View.VISIBLE);
boardsHandler.setCurrenBoard(numOfButton);
}};
newbutton.setOnClickListener(buttonListener);
// creating a thread to add button
buttons.post(new Runnable() {
#Override
public void run() {
buttons.addView(newbutton, p);
}
});
Is it something with the LinearLayout.LayoutParams p ?
Thanks!
Try following code
first do
LinearLayout myContainer = findViewById(R.id.layoutId);
When you set parameters for a view, they need to correspond to the parent view for your widget.
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
finally add button as you are doing.
try and tell if it works
Setting X and Y position will not work. The LinearLayout layouts it's children vertically or horizontally, only taking their width/height into account.
Besides this -- have you tried calling buttons.invalidate() after buttons.addView(...). This should refresh the layout and should show your newbutton.
This is a rather old post but I found it quickly when doing research on that kind of problem. So I'll post am answer anyway, maybe it'll be of help to anyone..
I had a similar problem with a relative layout to which buttons were added dynamically. I found a workaround in defining the layout's size manually when adding the buttons. For your case, adding the line
buttons.getLayoutParams().height = numOfButton*20+40;
after
buttons.addView(newbutton, p);
might help, though it's probably not the best solution.
I thought my mistake was using the RelativeLayout at all, but since you appear to have the same problem...
Ever thought of using a table layout?
I want to set the background color of an entire line in TextView and not necessarily the part of the line covered by text (which I can do by using Span).
E.g. If say line 0, can accomodate 25 characters, but only has 12 characters. If I say
SpannableString s = new SpannableString("abcdefghijkl");
s.setSpan(new BackgroundColorSpan(0xffffffff), 0, 11, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
TextView t = new TextView();
t.setText(s);
This would set background color of half the line.
But I want to have the entire line (entire width of TextView) to be filled with the background color. Also I want this to happen for only one line, not the entire TextView background.
Any idea how this can be achieved?
Wrap your TextView in a RelativeLayout, and put another view behind it:
<RelativeLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<View android:id="#+id/bgcolor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/whatever"
/>
<TextView android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Now, on global layout, find the height of a line of your TextView, and set the bgcolor view to that height:
final TextView textView = (TextView) findViewById(R.id.textview);
final ViewTreeObserver vto = textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int lineHeight = textView.getLineHeight();
// May need to also getLineSpacingExtra, etc. not sure.
View bgColor = findViewById(R.id.bgcolor);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)
bgColor.getLayoutParams();
lp.height = lineHeight;
bgColor.setLayoutParams(lp);
// May or may not want to remove the listener:
vto.removeGlobalOnLayoutListener(this);
}
}
Your goal is to use something like LineaLayout with vertical orientation,
that will have TextView as a "colorable line".
1) Create a class that extends LinearLayout.
2) Write basic functions to add "colorable line","paint it" & e.t.c.
3) Use your view in layouts XML.
TextView name = (TextView) findViewById(R.id.name);
String iName = "YOYOYOYO";
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(184, 184,
184));
SpannableString ssb = new SpannableString(iName);
ssb.setSpan(fcs, 0, iName.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
name.setText(ssb);
TextView (just like every other android View) have the method setBackgroundColor
t.setBackgroundColor(0xffffffff);