I want to draw a simple ImageView in the middle of the screen, horizontally and vertically. But i want to do it without using XML files, i need to do it programatically.
I tryed with the next code, but it doesn't works fine, it draws the image a little to the right and a little to the bottom. How to solve it?
ARImage = new ImageView(getApplicationContext());
ARImage.setImageResource(R.drawable.x);
rl.addView(ARImage); //rl is the relative layout that it's inserted into a frame layout
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
position.leftMargin = (int)(w/2);
position.topMargin = (int)(h/2);
ARImage.setLayoutParams(position);
It works for me like this:
package pete.android.study;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class Main extends Activity {
/*
* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView ARImage = new ImageView(getApplicationContext());
ARImage.setImageResource(R.drawable.icon);
RelativeLayout rl = new RelativeLayout(this);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int w = display.getWidth();
int h = display.getHeight();
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ARImage.setLayoutParams(position);
position.addRule(RelativeLayout.CENTER_IN_PARENT);
rl.addView(ARImage, position);
setContentView(rl);
}
}
Try to use
position.leftMargin = (int)(w/2 - whalf);
position.topMargin = (int)(h/2 - hhalf);
where whalf and hhalf are halfs of your image parameters.
I don't think you can set the left and top margin like that:
position.leftMargin = (int)(w/2);
position.topMargin = (int)(h/2);
Try setting the margins like this:
position.setMargins((int)(w/2), (int)(h/2), 0, 0); // left, top, right, bottom
Knowing that it is inside of RelativeLayout, you can place it in center of this layout:
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
rl.addView(ARImage, lp);
Related
I have placed programmatically generated FancyButtons on LinearLayout. But, the generated buttons are placed too compactly, in other words, there is no separation between two successive buttons. Also, I want the buttons to stretch entire with of the layout. I tried btnWordList.setMinimumWidth(MATCH_PARENT) without any result. Please find the code below.
FlexDict.java
package in.dipanjan.flexdict;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.graphics.Color;
import android.content.Intent;
import android.widget.LinearLayout;
import android.graphics.PixelFormat;
import mehdi.sakout.fancybuttons.FancyButton;
import android.support.v7.app.ActionBarActivity;
public class FlexDict extends ActionBarActivity implements View.OnClickListener {
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int listCount, wordLists = 5;
/* http://stackoverflow.com/questions/19078461/android-null-pointer-exception-findviewbyid */
setContentView(R.layout.activity_flex_dict);
LinearLayout container = (LinearLayout)findViewById(R.id.container);
for(listCount = 1; listCount <= wordLists; listCount++)
{
/* https://github.com/medyo/fancybuttons */
FancyButton btnWordList = new FancyButton(this);
btnWordList.setId(listCount);
btnWordList.setText("WordList " + listCount);
btnWordList.setBackgroundColor(Color.parseColor("#3b5998"));
btnWordList.setFocusBackgroundColor(Color.parseColor("#5474b8"));
btnWordList.setTextSize(20);
btnWordList.setIconResource("\uf04b");
btnWordList.setRadius(10);
btnWordList.setOnClickListener(this);
container.addView(btnWordList);
}
setContentView(container);
}
#Override
public void onClick(View view) {
int wordList = view.getId();
/*
* http://www.java-samples.com/showtutorial.php?tutorialid=1525
* http://stackoverflow.com/questions/7980627/pressing-back-button-did-not-go-back-to-previous-activity-android
*/
Bundle params = new Bundle();
params.putInt("WordList", wordList);
Intent intent = new Intent(this, ShowList.class);
intent.putExtras(params);
startActivity(intent);
}
}
activity_flex_dict.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/radialback">
</LinearLayout>
UI
http://s26.postimg.org/rkb0r4ys9/Fancy_Button.png
You need to setLayoutParams on your View.
i.e. btnWordList.setLayoutParams(new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT));
You need to set layout params for any view even if instantiated in XML or Programatically.
http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)
Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
You need to set a margin between your buttons to make a gab between your buttons. and set your width to match_parent to make the button stretch to the width of the layout
int marginBottom = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
5,
r.getDisplayMetrics()
);
for(listCount = 1; listCount <= wordLists; listCount++)
{
/* https://github.com/medyo/fancybuttons */
FancyButton btnWordList = new FancyButton(this);
btnWordList.setId(listCount);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, marginBottom);
btnWordList.setLayoutParams(params);
btnWordList.setText("WordList " + listCount);
btnWordList.setBackgroundColor(Color.parseColor("#3b5998"));
btnWordList.setFocusBackgroundColor(Color.parseColor("#5474b8"));
btnWordList.setTextSize(20);
btnWordList.setIconResource("\uf04b");
btnWordList.setRadius(10);
btnWordList.setOnClickListener(this);
container.addView(btnWordList);
}
You can use LayoutParam with margin
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
lp.bottumMargin = 2;
// or
lp.setMargins(0,0,0,2);
btnWordList.setLayoutParams(lp);
I have an activity that makes a layout programmatically from a Shared Preference using a for loop. The text views and buttons are enclosed in a linear layout. The user can input as many views as he wants. Now, the button will be a delete button. When pressed, I want to delete the linear layout the button and the other textviews are contained. How do I do this?
HERE IS MY CODE:
package com.dirkjan.myschools;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout subjectLeft, subjectRight;
Button addSubj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subjectLeft = (LinearLayout) findViewById(R.id.llSubjectLeft);
subjectRight = (LinearLayout) findViewById(R.id.llSubjectRight);
//Load the saved subjects
SharedPreferences getSubjects = getSharedPreferences("SubjectInfo_Prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = getSubjects.edit();
int subjectCount = getSubjects.getInt("count", 0);
if (subjectCount > 0 ){
for (int i = 1; i <= subjectCount; i++){
//Set the linear layout for each subject
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams llParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
float scale = getResources().getDisplayMetrics().density;
//SET BOTTOM MARGIN
float margin = 5; //RESIZE MARGIN HERE!
int margs = (int) (margin * scale + 0.5f);
//SET PADDING IN DP
float padding = 5; //RESIZE PADDING HERE!
int pads = (int) (padding * scale +0.5f);
llParams.setMargins(0,0,0,margs);
//SETTING THE LINEARLAYOUT PARAMS
ll.setLayoutParams(llParams);
ll.setPadding(pads, pads, pads, pads);
//SETTING THE BACKGROUND COLOR OF THE LINEAR LAYOUT
String chosenColor = getSubjects.getString("chosenColor" + i, "BLUE");
if (chosenColor.equals("Green")){
ll.setBackgroundResource(R.color.HoloGreen);
}else if (chosenColor.equals("Blue")){
ll.setBackgroundResource(R.color.HoloBlue);
}else if (chosenColor.equals("Gray")){
ll.setBackgroundResource(R.color.HoloGray);
}else if (chosenColor.equals("Orange")){
ll.setBackgroundResource(R.color.HoloOrange);
}else {
ll.setBackgroundResource(R.color.HoloYellow);
}
//ADDING THE LAYOUT TO THE APPROPRIATE CONTAINER (LEFT OR RIGHT)
if (i % 2 == 1){
subjectLeft.addView(ll);
} else {
subjectRight.addView(ll);
}
//SETTING THE SUBJECT NAME TEXTVIEW
TextView SubjectName = new TextView(this);
SubjectName.setText(getSubjects.getString("subjectName" + i, "Error"));
SubjectName.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
SubjectName.setTextSize(22);
SubjectName.setTypeface(Typeface.DEFAULT_BOLD);
//SETTING THE SUBJECT NUMB TEXT VIEW
TextView SubjectNumber = new TextView(this);
SubjectNumber.setText(getSubjects.getString("subjectNumb" + i, "Error"));
SubjectNumber.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
SubjectNumber.setTextSize(16);
//Creating the divider line
ImageView divider = new ImageView(this);
LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
divider.setLayoutParams(dividerParams);
divider.setBackgroundResource(R.color.Black);
//Add Views into the Layout
ll.addView(SubjectNumber);
ll.addView(SubjectName);
ll.addView(divider);
}
}
addSubj = (Button) findViewById(R.id.buttonPlusSubject);
addSubj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent toAddSubj = new Intent(MainActivity.this,
AddSubjectActivity.class);
startActivity(toAddSubj);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Please do take note that no id is assigned for each layout. It would help if there is a code to identify the parent of the parent of the button (The button is in a relative layout, which is in a linear layout where the linear layout must be removed by clicking the button.
First find your parent layout using
ll = (LinearLayout) findViewById(R.id.main_linearlayout);
get the child layout using
final LinearLayout child = (LinearLayout) ll.findViewById(count);
now to remove the whole layout you can use removeview() method as below
ll.removeView(child);
to only remove all views from the particular layout(here for eg. child) you can use
child.removeAllViews();
You can call view.setVisiblility(View.GONE) if you want to remove it from the layout, or view.setVisibility(View.INVISIBLE) if you just want to hide it.
You can remove a Child View from a parent by calling removeView(View view), for example like this :
parent.removeView(child);
Supposing that your LinearLayout ID is my_linear_layout, just do this in your onClickListener:
findViewById(R.id.my_linear_layout).setVisibility(View.GONE);
In your XML, be sure to put the ID:
<LinearLayout
android:id="#+id/my_linear_layout"
...>
</LinearLayout>
you can do this like get the id of the currently clicked item
and assigned in root layout
LinearLayout layout = (LinearLayout) v.getParent();
And remove using this code given below:
linearLayout.removeView(layout);
I need to overlap an image view with textview. And this combined view will be repeated 100 times in a LinearLayout. I was thinking of using FrameLayout in LinearLayout and Repeating the FrameLayout in LinearLayout 100 times when FrameLayout holds the imageview and textview overlapped.
Need to do this programatically not from xml file.
I added the image and textview to framelayout first then tried to add the framelayout to linearlayout. But it says : the specified child has already a parent.. so not working. Can you please show me in code? Thanks for your help.
it is going to be like this, but need to be done programmaticaly
---linear layout--------------
------------------------------
|frame layout----------------|
||txt view on top of img view|
------------------------------
frame layout will be repeated|
---/end of linear layout------
Also here is the separated code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout dynamicview = (LinearLayout) findViewById(R.id.main_layout);
FrameLayout barFrameLayout = new FrameLayout(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
Gravity.CENTER);
barFrameLayout.setLayoutParams(params);
LinearLayout.LayoutParams slparams1 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i = 65; i <= 75; i++) {
TextView catTV = new TextView(this);
catTV.setLayoutParams(slparams1);
catTV.setText("===" + Character.toString((char) i) + "===");
catTV.setTextSize(32);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.ic_launcher);
iv.setLayoutParams(slparams1);
barFrameLayout.addView(catTV);
barFrameLayout.addView(iv);
dynamicview.addView(barFrameLayout);
}
}
Here is the code to demonstrate what you are trying to achieve. I have used RelativeLayout, which is very flexible, you can position the elements easily relative to others.( if you need to change to FrameLayout you can change ).
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ExampleLayout extends LinearLayout{
public ExampleLayout(Context context,AttributeSet attrs){
super(context,attrs);
for(int i =0; i< 100; i++){
RelativeLayout childLayout = new RelativeLayout(context);
ImageView img = new ImageView(context);
TextView text = new TextView(context);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
childLayout.addView(img, params);
params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
childLayout.addView(text, params);
LinearLayout.LayoutParams parentParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
this.addView(childLayout,parentParams);
}
}
}
You can then use the ExampleLayout class to add it to any of the layout.xml file.
FrameLayout is designed to block out an area on the screen to display
a single item
(source: http://developer.android.com/reference/android/widget/FrameLayout.html).
Anyway, you have to create new FrameLayouts not use the same.
When you're doing:
barFrameLayout.addView(catTV);
barFrameLayout.addView(iv);
dynamicview.addView(barFrameLayout);
you're always adding these new objects (catTV and iv) to the same instance of a FrameLayout (barFrameLayout).
I don't think that's what you wanted to do.
I am using scrollBy() on a RelativeLayout to try to scroll over to buttons to the right of the visible screen, but I only see blank screen.
Buttons on the screen border get clipped, and remain clipped after scrolling (in any direction).
I have tried nearly every combination of WRAP CONTENT and FILL PARENT on the relativelayout params.
I also tried using a LinearLayout in the setContentview(), it didn't work.
I need the view to scroll horizontally, and the app is set to be always in landscape mode.
Does the layout have to be redrawn or refreshed in some manner to enable the missing buttons to appear?
Do I need to use some other view type for this kind of functionality?
Thanks for any input.
-nathan
Here is all the code from top, to end of onCreate():
package golfcaddy.tools;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class GolfScoreRel extends Activity implements OnClickListener {
// Settings file, preferences
public static final String PREFS_NAME = "golfscore";
public static final String PREFS_SCORES = "scores";
public static final String PREFS_BACKGROUND_IMAGE = "backimage";
SharedPreferences mSettings;
private int currentX = 0;
private int currentY = 0;
int numHoles = 0;
int numplayers = 0;
RelativeLayout r1;
LinearLayout lin;
public int mLastScoreEntered;
//manages unique ID's for all view inside Relative layouts
int viewCount = 1;
// int holeScoresFront[] = new int[9];
// int holeScoresFrontb[] = new int[9];
Button mLastClicked;
Button exitButton;
TextView pTotal1;
TextView pTotal2;
#Override
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// lin = new LinearLayout(this);
// lin.setOrientation(LinearLayout.VERTICAL);
/* not used yet....
GolfPlayer p1 = new GolfPlayer("P 1");
GolfPlayer p2 = new GolfPlayer("P 2");
GolfPlayer p3 = new GolfPlayer("P 3");
GolfPlayer p4 = new GolfPlayer("P 4");
*/
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
r1 = new RelativeLayout(this); // this layout will be set for contentview
r1.setLayoutParams(params);
numplayers = 4; //standard golf group
numHoles = 18; //standard golf round
r1.addView(createCard(numplayers,numHoles));
setContentView(r1);
} //end oncreate
here's my r1.scrollBy() code I borrowed from someplace:
Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
currentX = (int) event.getRawX();
currentY = (int) event.getRawY();
break;
}
case MotionEvent.ACTION_MOVE: {
int x2 = (int) event.getRawX();
int y2 = (int) event.getRawY();
r1.scrollBy(currentX - x2 , currentY - y2);
currentX = x2;
currentY = y2;
break;
}
case MotionEvent.ACTION_UP: {
break;
}
}
return true;
}
Screen Shots notes: We should be seeing 8 more buttons to the right.
Last shot shows a 5 player card with DEBUG button clipped.
Dang,as a new user, I'm not allowed to post images. try viewing them here: http://groups.yahoo.com/group/nateandroiddev/photos/album/776905892/pic/list?mode=tn&order=ordinal&start=1&dir=asc
A couple of things to try since I don't have all the code:
Try adding a postInvalidate() to the end of your ACTION_MOVE case. This will cause the screen to get redrawn.
You probably want to add a call to super() in your onTouchEvent method.
If these don't help, a screen shot of your situation would help to clarify what is happening. It sounds like after scrolling the screen is not being invalidated so you are scrolling an old drawing of the relative layout without causing it to get redrawn.
Does anyone know how to perform or have a good reference for doing an activity layout at runtime in android?
Here is the code for my activity. I'm sure I'm just neglecting to do something here:
package com.isi.sa;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SimpleAssessmentTest extends Activity {
LinearLayout layout;
TextView question;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
layout = new LinearLayout(this);
question = new TextView(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
layout.setBackgroundColor(R.color.blue);
question.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
question.setTextColor(R.color.green);
question.setTextSize(1,14);
question.setText("This is question1");
layout.addView(question);
setContentView(layout);
}
}
As you can see I'm just trying to add a linear layout with a single text view (just for testing purposes) however, when the activity starts I just get a black screen with a title bar of my app name.
Thanks
You forgot to set your contentView. You should add
setContentView(layout);
At the end of the onCreate method
You can check out this URL: http://www.linux-mag.com/cache/7705/1.html . It has both library widgets and custom widgets.
EDIT:
setBackgroundColor requires input in proper ARGB format: 0xAARRGGBB. Each AA, RR, GG and BB range from 00 (minimum) to ff (maximum).
The bare minimum example goes here and it works flawlessly. Here are the screenshot and code (modified a bit):
http://picturepush.com/public/3313522 (old)
package us.simpleit;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class SimpleGUI extends Activity {
TextView tv;
EditText et;
LinearLayout ll;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LinearLayout ll = new LinearLayout(this);
ll = new LinearLayout(this);
ll.setOrientation(android.widget.LinearLayout.VERTICAL);
ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
// ARGB: Opaque Red
ll.setBackgroundColor(0x88ff0000);
tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
tv.setText("sample text goes here");
// ARGB: Opaque Green
tv.setBackgroundColor(0x5500ff00);
ll.addView(tv);
et = new EditText(this);
et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
et.setText("edit me please");
// ARGB: Solid Blue
et.setBackgroundColor(0xff0000ff);
ll.addView(et);
Button btn = new Button(this);
btn.setText("Go!");
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
tv.setText(et.getText().toString());
}
});
ll.addView(btn);
setContentView(ll);
//setContentView(R.layout.main);
}
}
The following demonstrates how to create views and layouts programmatically without using the layout xml files. It also creates a rounded rectangle layout object that draws a rounded rectangle around any child objects that are placed in it.
package android.example;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MessageScreen extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int mainBackgroundColor = Color.parseColor("#2E8B57");
int labelTextColor = Color.parseColor("#FF4500");
int messageBackgroundColor = Color.parseColor("#3300FF");
int messageTextColor = Color.parseColor("#FFFF00");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
int minMarginSize = Math.round(density * 8);
int paddingSize = minMarginSize * 2;
int maxMarginSize = minMarginSize * 4;
TextView label = new TextView(this);
/*
* The LayoutParams are instructions to the Layout that will contain the
* View for laying out the View, so you need to use the LayoutParams of
* the Layout that will contain the View.
*/
LinearLayout.LayoutParams labelLayoutParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
label.setLayoutParams(labelLayoutParams);
label.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
label.setPadding(paddingSize, paddingSize, paddingSize, paddingSize);
label.setText(R.string.title);
label.setTextColor(labelTextColor);
TextView message = new TextView(this);
RoundedRectangle.LayoutParams messageLayoutParams = new RoundedRectangle.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
/*
* This is one of the calls must made to force a ViewGroup to call its
* draw method instead of just calling the draw method of its children.
* This tells the RoundedRectangle to put some extra space around the
* View.
*/
messageLayoutParams.setMargins(minMarginSize, paddingSize,
minMarginSize, maxMarginSize);
message.setLayoutParams(messageLayoutParams);
message.setTextSize(TypedValue.COMPLEX_UNIT_SP, paddingSize);
message.setText(R.string.message);
message.setTextColor(messageTextColor);
message.setBackgroundColor(messageBackgroundColor);
RoundedRectangle messageContainer = new RoundedRectangle(this);
LinearLayout.LayoutParams messageContainerLayoutParams = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
messageContainerLayoutParams.setMargins(paddingSize, 0, paddingSize, 0);
messageContainer.setLayoutParams(messageContainerLayoutParams);
messageContainer.setOrientation(LinearLayout.VERTICAL);
/*
* This is one of the calls must made to force a ViewGroup to call its
* draw method instead of just calling the draw method of its children.
* This tells the RoundedRectangle to color the the exta space that was
* put around the View as well as the View. This is exterior color of
* the RoundedRectangle.
*/
messageContainer.setBackgroundColor(mainBackgroundColor);
/*
* This is one of the calls must made to force a ViewGroup to call its
* draw method instead of just calling the draw method of its children.
* This is the interior color of the RoundedRectangle. It must be
* different than the exterior color of the RoundedRectangle or the
* RoundedRectangle will not call its draw method.
*/
messageContainer.setInteriorColor(messageBackgroundColor);
// Add the message to the RoundedRectangle.
messageContainer.addView(message);
//
LinearLayout main = new LinearLayout(this);
LinearLayout.LayoutParams mainLayoutParams = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
main.setLayoutParams(mainLayoutParams);
main.setOrientation(LinearLayout.VERTICAL);
main.setBackgroundColor(mainBackgroundColor);
main.addView(label);
main.addView(messageContainer);
setContentView(main);
}
}
The class for RoundedRectangle layout object is as defined here:
/**
* A LinearLayout that draws a rounded rectangle around the child View that was added to it.
*/
package android.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.LinearLayout;
/**
* A LinearLayout that has rounded corners instead of square corners.
*
* #author Danny Remington
*
* #see LinearLayout
*
*/
public class RoundedRectangle extends LinearLayout {
private int mInteriorColor;
public RoundedRectangle(Context p_context) {
super(p_context);
}
public RoundedRectangle(Context p_context, AttributeSet attributeSet) {
super(p_context, attributeSet);
}
// Listener for the onDraw event that occurs when the Layout is drawn.
protected void onDraw(Canvas canvas) {
Rect rect = new Rect(0, 0, getWidth(), getHeight());
RectF rectF = new RectF(rect);
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) getContext();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;
int arcSize = Math.round(density * 10);
Paint paint = new Paint();
paint.setColor(mInteriorColor);
canvas.drawRoundRect(rectF, arcSize, arcSize, paint);
}
/**
* Set the background color to use inside the RoundedRectangle.
*
* #param Primitive int - The color inside the rounded rectangle.
*/
public void setInteriorColor(int interiorColor) {
mInteriorColor = interiorColor;
}
/**
* Get the background color used inside the RoundedRectangle.
*
* #return Primitive int - The color inside the rounded rectangle.
*/
public int getInteriorColor() {
return mInteriorColor;
}
}
I'm not sure if this question has been answered or not, but I just overcame this same issue today. Viet touched on the issue above but did not explicitly point out to check your color values. If you're coming from J2ME background like myself, you might be defining your color int values as 0xRRGGBB, so for full red J2ME would define it as 0xFF0000. However, doing so on Android will result in an int value of 0x00FF0000. Because Android uses the format of 0xAARRGGBB, a value of 0xFF0000 (J2ME) is actually (0x00FF0000) in Android this is full Red color that is COMPLETLY TRANSPARENT, so it's not seen on screen.
I Noticed above in your code you're using question.setTextColor(R.color.green); This statement will assign the id value created in the R file, so it's probably a high number with some value as 0x7f050000 where the Alpha is set lower than FULL OPAQUE. Try your example with:
question.setTextColor( getResources().getColor( R.color.green ) );
This should set the text color to the value in R.color.green not the ID of R.color.green.