EditText ,Entered text not visible full - android

A sample code where i need to have a Edit Text in a Grid Layout Programatically .But when the text are entered in the app ,Only the small bottom portion of text is visible .The text is larger than expected. I need the edit text with text as shown in image which is Edit Text green background with only one line edit text required.Thanks
package com.example.myapplicationtesting;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity
{
#SuppressLint("ResourceType")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//LinearLayout linearLayout = findViewById(R.id.GroupContainer);
GridLayout Glyout;// = findViewById(R.id.Glayout_item);
Glyout = (GridLayout)findViewById(R.id.id_grid) ;
Glyout.setColumnCount(4);
Glyout.setRowCount(20);
int rowIndex = 0 ;
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = 50;//ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}
}
}
enter image description here

try setting param.height = 50; to WRAP_CONTENT
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}

Related

Android: Speed up dynamic UI generation

I have the following class which generates a calendar view. I'm not too fond of the built-in one, and am trying to gain more control over its appearance. However rendering the new UI (e.g. upon swipe) is taking 1-2 seconds to draw. Is there any place I could speed this up? Am testing on HTC One S (2012 model)
Should be relatively straightforward to follow:
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.joda.time.LocalDate;
import java.util.ArrayList;
public class Calendar extends AppCompatActivity {
private LocalDate _currentSelectedDate = new LocalDate();;
private LocalDate _today = new LocalDate();;
private float x1 = 0;
private float x2 = 0;
private float y1 = 0;
private float y2 = 0;
private TableLayout _tableLayout;
private RelativeLayout _relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
_relativeLayout = (RelativeLayout) findViewById(R.id.calendarLayout);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
#Override
public boolean onTouchEvent(MotionEvent touchevent)
{
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
// up
if (y1 > y2)
{
_currentSelectedDate = _currentSelectedDate.plusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
// down
if (y1 < y2)
{
_currentSelectedDate = _currentSelectedDate.minusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
break;
}
}
return false;
}
private void recreateUI(int year, int month)
{
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
_tableLayout = new TableLayout(this);
_tableLayout.setLayoutParams(lp);
_tableLayout.setStretchAllColumns(true);
_relativeLayout.removeAllViews();
_relativeLayout.addView(_tableLayout);
LocalDate date = new LocalDate().withYear(year).withMonthOfYear(month).dayOfMonth().withMinimumValue();
LocalDate last = date.dayOfMonth().withMaximumValue();
addMonthNameToUi(date);
addDaysNamesToUi();
addDayNumberssToUi(date, last);
}
private void addMonthNameToUi(LocalDate date) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT);
params.span = 7;
TextView t = new TextView(this);
t.setLayoutParams(params);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
t.setText(date.toString("MMM yyyy"));
row.addView(t);
float d = getResources().getDisplayMetrics().density;
int margin = (int)(20 * d);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) t.getLayoutParams();
mlp.setMargins(mlp.leftMargin, mlp.topMargin, mlp.rightMargin, margin);
_tableLayout.addView(row);
}
private void addDaysNamesToUi() {
TableRow dayNameRow = new TableRow(this);
addMonth(dayNameRow, "Mon");
addMonth(dayNameRow, "Tue");
addMonth(dayNameRow, "Wed");
addMonth(dayNameRow, "Thu");
addMonth(dayNameRow, "Fri");
addMonth(dayNameRow, "Sat");
addMonth(dayNameRow, "Sun");
_tableLayout.addView(dayNameRow);
}
private void addDayNumberssToUi(LocalDate date, LocalDate last) {
TableRow row = null;
int columnsCount = 0;
boolean firstRow = true;
while (date.isBefore(last) || date.isEqual(last)) {
if (columnsCount == 0) {
row = new TableRow(this);
_tableLayout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT, 1.0f));
// blank columns for days not at the start of month
if (firstRow) {
firstRow = false;
int i = 1;
for (; i < date.getDayOfWeek(); i++) {
addDayNumberToRow(row, date, "");
}
columnsCount += i - 1;
date.plusDays(i - 1);
}
}
addDayNumberToRow(row, date, String.valueOf(date.getDayOfMonth()));
date = date.plusDays(1);
columnsCount++;
if (columnsCount == 7)
columnsCount = 0;
}
while (row.getChildCount() < 7)
addDayNumberToRow(row, date, "");
}
private void addMonth(TableRow row, String month)
{
TextView t = new TextView(this);
t.setText(month);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
row.addView(t);
}
private void addDayNumberToRow(TableRow row, final LocalDate date, String text)
{
TextView v = new TextView(this);
v.setText(text);
v.setGravity(Gravity.CENTER);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));
if (date.getDayOfMonth() == _today.getDayOfMonth() && date.getMonthOfYear() == _today.getMonthOfYear() && date.getYear() == _today.getYear()) {
v.setTypeface(v.getTypeface(), Typeface.BOLD);
v.setTextSize(v.getTextSize() + 1);
}
ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Paint.Style.STROKE);
border.getPaint().setColor(Color.BLACK);
v.setBackground(border);
row.addView(v);
}
}
Your "recreateUI" method do alot of stuff like creating new views. Avoid creating new objects by reusing those already created.
Usually calendar views are quite complex. You most likely wont achieve smooth framerate by using multiple views in such way. You would have to write custom view witch will draw itself.
Turns out a lot of the slowdown was caused from running the application under debug mode -- running it normally resulted in acceptable performance.

create vertical lines in seekbar

I'm trying to create something like this. The problem is how to create vertical lines close to the seekbar. I tried the code given here, but the seekbar line disappears. Any help would be appreciated. Here is what I've done so far.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar sb = (SeekBar)findViewById(R.id.seekBar1);
//Get the width of the main view.
Display display = getWindowManager().getDefaultDisplay();
Point displaysize = new Point();
display.getSize(displaysize);
int width = displaysize.x;
//set the seekbar maximum (Must be a even number, having a remainder will cause undersirable results)
//this variable will also determine the number of points on the scale.
int seekbarmax = 10;
int seekbarpoints = (width/seekbarmax); //this will determine how many points on the scale there should be on the seekbar
//find the seekbar in the view, and set some behaviour properties
SeekBar seekbar = (SeekBar)findViewById(R.id.seekBar1);
//Set the seekbar to a max range of 10
seekbar.setMax(seekbarmax);
//Create a new bitmap that is the width of the screen
Bitmap bitmap = Bitmap.createBitmap(width, 100, Bitmap.Config.ARGB_8888);
//A new canvas to draw on.
Canvas canvas = new Canvas(bitmap);
//a new style of painting - colour and stoke thickness.
Paint paint = new Paint();
paint.setColor(Color.BLUE); //Set the colour to red
paint.setStyle(Paint.Style.STROKE); //set the style
paint.setStrokeWidth(1); //Stoke width
Paint textpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textpaint.setColor(Color.rgb(61, 61, 61));// text color RGB
textpaint.setTextSize(28);// text size
int point = 0; //initiate the point variable
//Start a for loop that will loop seekbarpoints number of times.
for (int i = 0; i < seekbarpoints; i++ ){
if ((i%2)==0) {
//short line
point = point + seekbarpoints;
canvas.drawLine(point, 30, point, 0, paint);
//drawLine(startx,startx,endy,endy)
}
//Create a new Drawable
Drawable d = new BitmapDrawable(getResources(),bitmap);
//Set the seekbar widgets background to the above drawable.
seekbar.setProgressDrawable(d);
}
}
}
I was searching for the this for long time and only got an answer to draw the numbers. Thus I decided to do it myself. I took the solution having only the steps and extended it by adding the logic for the intervals.
Please see the below image.
I then successfully created a seekbar with interval lables and vertical lines over seekbar. The above image is what I've achieved.
However there are few optimization in the padding which you can work on adjusting the dimensions.
Solution :
The xml file for the intervals:
seekbar_with_intervals_labels
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textViewInterval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#707070"/>
XML for the Vertical deviders : seekbar_vertical_lines
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textViewVerticalLine"
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#drawable/lines" />
Then the custom Seekbar class :
package com.example.abc.myapplication;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import com.example.abc.myapplication.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekbarWithIntervals extends LinearLayout {
private RelativeLayout RelativeLayout = null;
private SeekBar Seekbar = null;
private RelativeLayout Divider = null;
private View verticalLine = null;
private int WidthMeasureSpec = 0;
private int HeightMeasureSpec = 0;
public SeekbarWithIntervals(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
getActivity().getLayoutInflater()
.inflate(R.layout.seekbar_with_intervals, this);
}
private Activity getActivity() {
return (Activity) getContext();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
verticalLine = new View(getActivity());
verticalLine.setLayoutParams(new LayoutParams(2, LayoutParams.MATCH_PARENT));
verticalLine.setBackgroundColor(Color.BLACK);
if (changed) {
alignIntervals();
// We've changed the intervals layout, we need to refresh.
RelativeLayout.measure(WidthMeasureSpec, HeightMeasureSpec);
RelativeLayout.layout(RelativeLayout.getLeft(), RelativeLayout.getTop(), RelativeLayout.getRight(), RelativeLayout.getBottom());
}
}
private void alignIntervals() {
int widthOfSeekbarThumb = getSeekbarThumbWidth();
int thumbOffset = widthOfSeekbarThumb / 2;
int widthOfSeekbar = getSeekbar().getWidth();
int firstIntervalWidth = getRelativeLayout().getChildAt(0).getWidth();
int remainingPaddableWidth = widthOfSeekbar - firstIntervalWidth - widthOfSeekbarThumb;
int numberOfIntervals = getSeekbar().getMax();
int maximumWidthOfEachInterval = remainingPaddableWidth / numberOfIntervals;
alignFirstInterval(thumbOffset);
alignIntervalsInBetween(maximumWidthOfEachInterval);
alignLastInterval(thumbOffset, maximumWidthOfEachInterval);
}
private int getSeekbarThumbWidth() {
return getResources().getDimensionPixelOffset(R.dimen.seekbar_thumb_width);
}
private void alignFirstInterval(int offset) {
TextView firstInterval = (TextView) getRelativeLayout().getChildAt(0);
firstInterval.setPadding(offset - 10, 0, 0, 0);
TextView firstLine = (TextView) getDivider().getChildAt(0);
firstLine.setPadding(offset + 10, 0, 0, 0);
}
private void alignIntervalsInBetween(int maximumWidthOfEachInterval) {
int widthOfPreviousIntervalsText = 0;
int widthOfPreviousLine = 0;
// Don't align the first or last interval.
for (int index = 1; index < (getRelativeLayout().getChildCount() - 1); index++) {
TextView textViewInterval = (TextView) getRelativeLayout().getChildAt(index);
int widthOfText = textViewInterval.getWidth();
// This works out how much left padding is needed to center the current interval.
//int leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 2) - (widthOfPreviousIntervalsText / 2) - (widthOfText / 2));
int leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 2) - (widthOfPreviousIntervalsText / 2) - (widthOfText / index ) + index + 5 * 5);
textViewInterval.setPadding(leftPadding, 0, 0, 0);
widthOfPreviousIntervalsText = widthOfText;
TextView textViewLine = (TextView) getDivider().getChildAt(index);
int widthOfLine = textViewLine.getWidth();
// This works out how much left padding is needed to center the current interval.
leftPadding = (maximumWidthOfEachInterval + (index + (maximumWidthOfEachInterval / 10)) - (index * 4)); //Math.round(maximumWidthOfEachInterval + (widthOfLine ) + (widthOfPreviousLine ));
//leftPadding = Math.round((maximumWidthOfEachInterval - (widthOfPreviousLine / index) - (widthOfPreviousLine / index) - (widthOfPreviousLine / index)) + 10);
textViewLine.setPadding(leftPadding , 0, 0, 0);
widthOfPreviousLine = widthOfLine;
}
}
private void alignLastInterval(int offset, int maximumWidthOfEachInterval) {
int lastIndex = getRelativeLayout().getChildCount() - 1;
TextView lastInterval = (TextView) getRelativeLayout().getChildAt(lastIndex);
int widthOfText = lastInterval.getWidth();
int leftPadding = Math.round(maximumWidthOfEachInterval - widthOfText - offset);
lastInterval.setPadding(leftPadding + 20, 0, 0, 0);
TextView lastLine = (TextView) getDivider().getChildAt(lastIndex);
leftPadding = Math.round(maximumWidthOfEachInterval - (widthOfText / 5) - (widthOfText / 5) - (widthOfText / 5 ) + 3 * 10);
lastLine.setPadding(leftPadding , 0, 0, 0);
}
protected synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
WidthMeasureSpec = widthMeasureSpec;
HeightMeasureSpec = heightMeasureSpec;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int getProgress() {
return getSeekbar().getProgress();
}
public void setProgress(int progress) {
getSeekbar().setProgress(progress);
}
public void setIntervals(List<String> intervals) {
displayIntervals(intervals);
getSeekbar().setMax(intervals.size() - 1);
}
private void displayIntervals(List<String> intervals) {
int idOfPreviousInterval = 0;
int idOfPreviousLine = 0;
if (getRelativeLayout().getChildCount() == 0) {
for (String interval : intervals) {
TextView textViewInterval = createInterval(interval);
alignTextViewToRightOfPreviousInterval(textViewInterval, idOfPreviousInterval);
TextView textViewVerticaLine = createVerticalLine();
alignTextViewToRightOfPreviousInterval(textViewVerticaLine, idOfPreviousLine);
idOfPreviousLine = textViewVerticaLine.getId();
idOfPreviousInterval = textViewInterval.getId();
getRelativeLayout().addView(textViewInterval);
getDivider().addView(textViewVerticaLine);
}
}
}
private TextView createInterval(String interval) {
View textBoxView = (View) LayoutInflater.from(getContext())
.inflate(R.layout.seekbar_with_intervals_labels, null);
TextView textView = (TextView) textBoxView
.findViewById(R.id.textViewInterval);
textView.setId(View.generateViewId());
textView.setText(interval);
return textView;
}
private TextView createVerticalLine() {
View textBoxView = (View) LayoutInflater.from(getContext())
.inflate(R.layout.seekbar_vertical_lines, null);
TextView textView = (TextView) textBoxView
.findViewById(R.id.textViewVerticalLine);
textView.setId(View.generateViewId());
return textView;
}
private void alignTextViewToRightOfPreviousInterval(TextView textView, int idOfPreviousInterval) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (idOfPreviousInterval > 0) {
params.addRule(RelativeLayout.RIGHT_OF, idOfPreviousInterval);
}
textView.setLayoutParams(params);
}
public void setOnSeekBarChangeListener(OnSeekBarChangeListener onSeekBarChangeListener) {
getSeekbar().setOnSeekBarChangeListener(onSeekBarChangeListener);
}
private RelativeLayout getRelativeLayout() {
if (RelativeLayout == null) {
RelativeLayout = (RelativeLayout) findViewById(R.id.intervals);
}
return RelativeLayout;
}
private SeekBar getSeekbar() {
if (Seekbar == null) {
Seekbar = (SeekBar) findViewById(R.id.seekbar);
}
return Seekbar;
}
private RelativeLayout getDivider() {
if (Divider == null) {
Divider = (RelativeLayout) findViewById(R.id.fl_divider);
}
return Divider;
}
}
Then the MainActivity where we dynamically add the intervals.
public class MainActivity extends AppCompatActivity {
private SeekbarWithIntervals SeekbarWithIntervals = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> seekbarIntervals = getIntervals();
getSeekbarWithIntervals().setIntervals(seekbarIntervals);
}
private List<String> getIntervals() {
return new ArrayList<String>() {{
add("45");
add("55");
add("65");
add("75");
add("85");
add("95");
}};
}
private SeekbarWithIntervals getSeekbarWithIntervals() {
if (SeekbarWithIntervals == null) {
SeekbarWithIntervals = (SeekbarWithIntervals) findViewById(R.id.seekbarWithIntervals);
}
return SeekbarWithIntervals;
}
}
You can put the padding bottom of the divider so as to push it upwards like in your image.
Note : You can also have a single layout defining the divider and the number layout.
You will need two PNG drawables one for background and one for progress.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#android:id/background"
android:drawable="#drawable/seekbar_drawable_frost" />
<item
android:id="#android:id/progress"
android:drawable="#drawable/seekbar_drawable_frost_progress" />
</layer-list>

Adding multiple TextView on runTime android

I'm trying to add multople TextViews to a relativeLayout on runtime.
the reason is that the list is to be created, depending on users choises.
I know how to add 1 textView. but when I entered the code to a loop and tried to creat more than 1, it just doesn't show anything..
pleas help,
int left=70,top=25;
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
EDIT: the full code of the activity:
package com.fgdvir.psychowords;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class WordTest extends Activity {
RelativeLayout testLayout;
int displayWidth, displayHeight;
ArrayList<String> startLetterPos = new ArrayList<String>();
//private int[] startLetterPos = new int[26];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.word_test);
startLetterPos = getIntent().getStringArrayListExtra("test");
testLayout = (RelativeLayout) findViewById(R.id.word_test);
create_questions();
// Get Screen size
/*
* Display display = getWindowManager().getDefaultDisplay(); Point size = new ` `Point(); display.getSize(size);
* displayWidth = size.x; displayHeight = size.y;
*/
}
public void create_questions() {
int left=70,top=25;
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
}
}
so I figured it out,
I still don't know why this doesn't work, but I found another way.
I added the text to a linearLayout, and then the linearLayout to my relative layout:
LinearLayout lL = new LinearLayout(this);
lL.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (int i = 0; i<26; i++){
String s = startLetterPos.get(i);
TextView tv = new TextView(this);
tv.setId(i);
tv.setText(s);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
if (i != 0 ){
params.addRule(RelativeLayout.BELOW, i-1);
}
lL.addView(tv,params);
}
testLayout.addView(lL);
}

Adding components to a layout via JAVA in android

Actually the main layout is a relative layout which interns contains a relative layout in it. The main objective is to add images to the inner relative layout .
I tried this out but didn't succeed . This is my code :
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.app.Activity;
import android.graphics.Point;
public class MainActivity extends Activity {
Display display;
Point point;
int width;
int height;
Animation up, down, right, left;
RelativeLayout rl, rl2;
Integer[] pics = { R.drawable.img1, R.drawable.img2,R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,R.drawable.img7, R.drawable.img8,
R.drawable.img9, R.drawable.img10,R.drawable.img11, R.drawable.img12,
R.drawable.img13, R.drawable.img14,R.drawable.img15};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
// TODO Auto-generated method stub
rl = (RelativeLayout) findViewById(R.id.Rlayout);
rl.setGravity(Gravity.CENTER);
int x = 0;
int y = 0;
for(int i = 1 ; i<16 ; i++ ){
ImageView img = new ImageView(this);
img.setImageResource(pics[i-1]);
int tempx = img.getWidth();
int tempy = img.getHeight();
rl.addView(img, x, y);
x += tempx;
if(i%4 == 0){
x = 0;
y += tempy;
}
}
rl.bringToFront();
}
}
The XML code for the layout being used is :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/R1Layout">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:id="#+id/Rlayout" >
</RelativeLayout>
</RelativeLayout>
The output that i get is a blank screen .
Help me out with a solution how to display the images within the inner relative layout
Thanks in advance ,
To insert images into the inner RelativeLayout, you need to use ImageView object. You can do it using the addView() method that is available to RelativeLayout (through inheritance from ViewGroup class). You can do it as follows within your activity (you have to decide where you want to place this):
RelativeLayout rl = (RelativeLayout) findViewById(R.id.Rlayout); // find inner layout
ImageView iview = new Image(this);
// Set image view parameters - refer to Android documentation for this
rl.addView(iview); // and so on.
// You can add as many items as you want to any layout you want in this manner
I think you are misunderstanding, x and y are not the coordinates, are width and height respectively in
rl.addView(img, x, y);
and you can´t get the size of the imageviews with:
int tempx = img.getWidth();
int tempy = img.getHeight();
You must use a container to set size and coordinates to your imageview´s:
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(100, 100);
params.leftMargin = x;
params.topMargin = y;
rl.addView(img,params);
this is an example of how to do it:
private void Init() {
// TODO Auto-generated method stub
int x = 0;
int y = 0;
rl = (RelativeLayout) findViewById(R.id.Rlayout);
rl.setGravity(Gravity.CENTER);
for(int i = 0 ; i<14 ; i++ ){
ImageView img = new ImageView(this);
img.setImageResource(pics[i]);
//int tempx = img.getWidth();
//int tempy = img.getHeight();
int tempx = 100;
int tempy = 100;
//rl.addView(img, x, y);
x += tempx;
if(i%4 == 0){
x = 0;
y += tempy;
}
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(100, 100);
params.leftMargin = x;
params.topMargin = y;
rl.addView(img,params);
}
rl.bringToFront();
}
like Rajesh, i recommend too the use of a Gridview instead of RelativeLayout.
See this example:
GridView and excess space padding

achartengine toScreenPoint(double) always returns nullPointerException

Every time I call this method it return nullpointerexception:
java.lang.NullPointerException at org.achartengine.chart.XYChart.toScreenPoint(XYChart.java:867)
I see mScreenR of chart is null
Without using this method toScreenPoint(double) the charts works well this is the code:
package com.insights.insights.gui;
import java.util.ArrayList;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.XYChart;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import com.insights.insights.R;
import com.insights.insights.local.ApplicationsController;
import com.insights.insights.model.AppMetrics;
import com.insights.insights.model.Application;
import com.insights.insights.model.Applications;
import com.insights.insights.model.Day;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class ChartFragment extends Fragment {
private XYMultipleSeriesRenderer renderer;
private XYMultipleSeriesDataset dataset;
private GraphicalView graphicalView;
private XYSeries firstSeries;
private XYChart chart=null;
private String apiKey;
private ArrayList<Day> days;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiKey = getArguments().getString(getString(R.string.tabs_activity_api_key));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chart_fragment, container, false);
v.findViewById(R.idChartFragment.container).requestFocus();
this.view = v;
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Obtaining data to plot
Applications applications = ApplicationsController.getInstance(getActivity()).getApplications();
ArrayList<Application> applicationArray = applications.getApplication();
if (applicationArray != null && !applicationArray.isEmpty()) {
for (int i = 0; i < applicationArray.size(); i++) {
if (applicationArray.get(i).getApiKey().equals(apiKey)) {
ArrayList<AppMetrics> appMetrics = applicationArray.get(i).getAppMetrics();
for (int j = 0; j < appMetrics.size(); j++) {
if (appMetrics.get(j).getMetric().equals("Sessions")) {
days = appMetrics.get(j).getDay();
break;
}
}
}
}
}
// If there isn't any item to plot and show a toast
if (days == null) {
Toast toast = Toast.makeText(getActivity(), R.string.chart_fragment_no_items, Toast.LENGTH_LONG);
toast.show();
return;
}
// Ploting the items
dataset = getDataset(days);
renderer = getRenderer();
setRendererStyling(renderer);
// add plot to the layout
if (graphicalView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.idChartFragment.Chart);
chart= new LineChart(dataset, renderer);
graphicalView = new GraphicalView(getActivity(), chart);
renderer.setSelectableBuffer(11);
layout.addView(graphicalView);
} else{
graphicalView.repaint();
}
if(chart!=null&&firstSeries!=null){
for(int i=0;i<firstSeries.getItemCount();i++){
double x = firstSeries.getX(i);
double y = firstSeries.getY(i);
double[] screenPoint = chart.toScreenPoint(new double[] { x, y },0);
Log.i("puntos", x + "," + y + " = "+" ("+screenPoint[0]+", "+screenPoint[1]+")");
}
}
}
/**
* Method for set the style of the plotter window and the string at the x
* axis
*
* #param mRenderer
* render to put style in
*
* #param dataSetX
* string to set at x axis
*/
private void setRendererStyling(XYMultipleSeriesRenderer mRenderer) {
mRenderer.setApplyBackgroundColor(false);
mRenderer.setMarginsColor(R.drawable.transperent_color);
mRenderer.setMargins(new int[] { 0, 0, 0, 0 });
mRenderer.setShowAxes(false);
mRenderer.setZoomButtonsVisible(false);
mRenderer.setExternalZoomEnabled(false);
mRenderer.setPointSize(20);
mRenderer.setClickEnabled(false);
mRenderer.setDisplayValues(false);
mRenderer.setXLabels(0);
mRenderer.setYLabels(0);
mRenderer.setPanEnabled(false);
mRenderer.setZoomEnabled(false);
mRenderer.setShowLegend(false);
}
/**
* Method to introduce the values of the y axis
*
* #param dataSetY
* data to set at axis y
* #return the data to set
*/
private XYMultipleSeriesDataset getDataset(ArrayList<Day> days) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
firstSeries = new XYSeries("");
for (int i = 0; i < 12; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
firstSeries.add(i, value);
}
dataset.addSeries(firstSeries);
return dataset;
}
/**
* Method for set the style of the line you want to plot and create a new
* renderer
*
* #return the renderer
*/
private XYMultipleSeriesRenderer getRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(getResources().getColor(R.color.grey_number_label_background));
r.setLineWidth(getResources().getInteger(R.integer.chart_fragment_line_width));
// r.setDisplayChartValues(true);
r.setPointStyle(PointStyle.POINT);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
return renderer;
}
}
And this is the layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+idChartFragment/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+idChartFragment/Chart"
android:layout_width="300dp"
android:layout_height="300dp"
android:orientation="horizontal"/>
<AbsoluteLayout
android:id="#+idChartFragment/absolute"
android:layout_width="300dp"
android:layout_height="300dp"/>
</RelativeLayout>
Second Edit:
I want to do something like this:
With my code I do this:
This is my code:
package com.insights.insights.gui;
import java.util.ArrayList;
import java.util.List;
import org.achartengine.GraphicalView;
import org.achartengine.chart.ClickableArea;
import org.achartengine.chart.LineChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.XYChart;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Layout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay.OnFocusChangeListener;
import com.insights.insights.R;
import com.insights.insights.local.ApplicationsController;
import com.insights.insights.model.AppMetrics;
import com.insights.insights.model.Application;
import com.insights.insights.model.Applications;
import com.insights.insights.model.Day;
/**
*
* #author Manuel Plazas Palacio
*
*/
public class ChartFragment extends Fragment {
private XYMultipleSeriesRenderer renderer;
private XYMultipleSeriesDataset dataset;
private GraphicalView graphicalView;
private XYSeries firstSeries;
private XYChart chart = null;
private AbsoluteLayout absoluteLayout;
private ImageView point;
private LinearLayout pointInfoConatiner;
private TextView pointNumberText;
private TextView pointNameText;
private TextView pointDateText;
private Typeface avenirHeavy;
private Typeface avenirLight;
private String apiKey;
private String metricName;
private ArrayList<Day> days;
// The max and the min values displayed
private double max = 0;
private double min = 0;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiKey = getArguments().getString(getString(R.string.tabs_activity_api_key));
metricName = "Sessions";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.chart_fragment, container, false);
v.findViewById(R.idChartFragment.container).requestFocus();
this.view = v;
absoluteLayout = (AbsoluteLayout) v.findViewById(R.idChartFragment.absolute);
// pointInfoConatiner = (LinearLayout) v.findViewById(R.idChartFragment.pointInfoContainer);
// pointNumberText = (TextView) v.findViewById(R.idChartFragment.pointNumberText);
// pointNameText = (TextView) v.findViewById(R.idChartFragment.pointNameText);
// pointDateText = (TextView) v.findViewById(R.idChartFragment.pointDateText);
//
// pointNameText.setText(metricName);
// Obtaining data to plot
Applications applications = ApplicationsController.getInstance(getActivity()).getApplications();
ArrayList<Application> applicationArray = applications.getApplication();
if (applicationArray != null && !applicationArray.isEmpty()) {
for (int i = 0; i < applicationArray.size(); i++) {
if (applicationArray.get(i).getApiKey().equals(apiKey)) {
ArrayList<AppMetrics> appMetrics = applicationArray.get(i).getAppMetrics();
for (int j = 0; j < appMetrics.size(); j++) {
if (appMetrics.get(j).getMetric().equals(metricName)) {
days = appMetrics.get(j).getDay();
break;
}
}
}
}
}
// If there isn't any item to plot and show a toast
if (days == null) {
Toast toast = Toast.makeText(getActivity(), R.string.chart_fragment_no_items, Toast.LENGTH_LONG);
toast.show();
}
// Ploting the items
dataset = getDataset(days);
renderer = getRenderer();
setRendererStyling(renderer);
// add plot to the layout
if (graphicalView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.idChartFragment.Chart);
chart = new LineChart(dataset, renderer);
graphicalView = new GraphicalView(getActivity(), chart);
renderer.setSelectableBuffer(11);
layout.addView(graphicalView);
} else {
graphicalView.repaint();
}
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
avenirHeavy = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Avenir Heavy.ttf");
avenirLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Avenir Light.ttf");
graphicalView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SeriesSelection seriesSelection = graphicalView.getCurrentSeriesAndPoint();
double[] xy = graphicalView.toRealPoint(0);
//creating the views
createOnClickPointsView();
if (seriesSelection != null) {
// debug
Log.d("Punto", seriesSelection.getXValue() + ", " + seriesSelection.getValue());
double x = firstSeries.getX(seriesSelection.getPointIndex() + 1);
double y = firstSeries.getY(seriesSelection.getPointIndex() + 1);
double[] screenPoint = chart.toScreenPoint(new double[] { x, y });
// debug
Log.d("Chart point", "Chart element in series index " + seriesSelection.getSeriesIndex() + " data point index "
+ seriesSelection.getPointIndex() + " was clicked" + " closest point value X=" + seriesSelection.getXValue()
+ ", Y=" + seriesSelection.getValue() + " clicked point value X=" + (float) xy[0] + ", Y=" + (float) xy[1]);
Log.d("Punto pantalla", " (" + screenPoint[0] + ", " + screenPoint[1] + ")");
int value = Integer.parseInt(days.get((int) (days.size() - (13 - x))).getValue());
String date = days.get((int) (days.size() - (13 - x))).getDate();
pointNumberText.setText(value + "");
pointDateText.setText(date);
// drawing point info
absoluteLayout.addView(pointInfoConatiner, new LayoutParams(getResources().getDrawable(R.drawable.graficapin)
.getIntrinsicWidth(), getResources().getDrawable(R.drawable.graficapin).getIntrinsicHeight(),
(int) (screenPoint[0] - (getResources().getDrawable(R.drawable.graficapin).getIntrinsicWidth() / 2)),
(int) (screenPoint[1] - (getResources().getDrawable(R.drawable.graficapin).getIntrinsicHeight()))));
// drawing point clicked
absoluteLayout.addView(point, new LayoutParams(getResources().getDrawable(R.drawable.puntoon).getIntrinsicWidth(),
getResources().getDrawable(R.drawable.puntoon).getIntrinsicHeight(), (int) (screenPoint[0] - (getResources()
.getDrawable(R.drawable.puntoon).getIntrinsicWidth() / 2)), (int) (screenPoint[1] - ((getResources()
.getDrawable(R.drawable.puntoon).getIntrinsicHeight()) / 4))));
}
}
});
}
/**
* Method for set the style of the plotter window and the string at the x
* axis
*
* #param mRenderer
* render to put style in
*
* #param dataSetX
* string to set at x axis
*/
private void setRendererStyling(XYMultipleSeriesRenderer mRenderer) {
mRenderer.setApplyBackgroundColor(false);
mRenderer.setMarginsColor(R.drawable.transperent_color);
mRenderer.setMargins(new int[] { 0, 0, 0, 0 });
mRenderer.setShowAxes(false);
mRenderer.setZoomButtonsVisible(false);
mRenderer.setExternalZoomEnabled(false);
mRenderer.setPointSize(getResources().getInteger(R.integer.chart_fragment_point_size));
mRenderer.setClickEnabled(true);
mRenderer.setDisplayValues(false);
mRenderer.setXLabels(0);
mRenderer.setYLabels(0);
mRenderer.setPanEnabled(true);
mRenderer.setZoomEnabled(false);
mRenderer.setShowLegend(false);
mRenderer.setYAxisMax(max + 10);
mRenderer.setYAxisMin(min - 10);
}
/**
* Method to introduce the values of the y axis
*
* #param dataSetY
* data to set at axis y
* #return the data to set
*/
private XYMultipleSeriesDataset getDataset(ArrayList<Day> days) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
firstSeries = new XYSeries("");
for (int i = 0; i < 12; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
firstSeries.add(i, value);
}
dataset.addSeries(firstSeries);
XYSeries secondSeries = new XYSeries("");
for (int i = 1; i < 11; i++) {
int value = Integer.parseInt(days.get(days.size() - (13 - i)).getValue());
if (i == 1) {
max = value;
min = value;
}
if (value > max)
max = value;
if (value < min)
min = value;
secondSeries.add(i, value);
}
dataset.addSeries(secondSeries);
return dataset;
}
/**
* Method for set the style of the line you want to plot and create a new
* renderer
*
* #return the renderer
*/
private XYMultipleSeriesRenderer getRenderer() {
XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
//First chart with the line
XYSeriesRenderer r = new XYSeriesRenderer();
r.setColor(getResources().getColor(R.color.grey_number_label_background));
r.setLineWidth(getResources().getInteger(R.integer.chart_fragment_line_width));
// r.setDisplayChartValues(true);
r.setPointStyle(PointStyle.POINT);
r.setFillPoints(true);
renderer.addSeriesRenderer(r);
// Second chart with the points
XYSeriesRenderer r1 = new XYSeriesRenderer();
r1.setColor(getResources().getColor(R.color.purple_chart_points));
r1.setLineWidth(0);
r1.setFillPoints(true);
r1.setPointStyle(PointStyle.CIRCLE);
renderer.addSeriesRenderer(r1);
return renderer;
}
public XYSeries getFirstSeries() {
return firstSeries;
}
public void setFirstSeries(XYSeries firstSeries) {
this.firstSeries = firstSeries;
}
public XYChart getChart() {
return chart;
}
public void setChart(XYChart chart) {
this.chart = chart;
}
/**
* Method for create the views when clicking on a point of the chart
*/
private void createOnClickPointsView() {
//If the info is already visible
if (pointInfoConatiner != null)
absoluteLayout.removeView(pointInfoConatiner);
// If the point is drawn
if (point != null)
absoluteLayout.removeView(point);
pointInfoConatiner = new LinearLayout(getActivity());
pointInfoConatiner.setBackgroundDrawable(getResources().getDrawable(R.drawable.graficapin));
pointInfoConatiner.setOrientation(LinearLayout.VERTICAL);
pointInfoConatiner.setGravity(Gravity.CENTER_HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 8, 0, 0);
pointNumberText = new TextView(getActivity());
pointNumberText.setTextSize(18);
pointNumberText.setTextColor(getResources().getColor(R.color.purple_chart_points));
pointNumberText.setTypeface(avenirHeavy);
pointNumberText.setGravity(Gravity.CENTER);
pointNameText = new TextView(getActivity());
pointNameText.setTextSize(18);
pointNameText.setTextColor(getResources().getColor(R.color.grey_users_label));
pointNameText.setTypeface(avenirLight);
pointNameText.setText(metricName);
pointNameText.setGravity(Gravity.CENTER);
pointDateText = new TextView(getActivity());
pointDateText.setTextSize(11);
pointDateText.setTextColor(getResources().getColor(R.color.grey_users_label));
pointDateText.setTypeface(avenirHeavy);
pointDateText.setGravity(Gravity.CENTER);
pointInfoConatiner.addView(pointNumberText, 0, layoutParams);
layoutParams.setMargins(0, 2, 0, 0);
pointInfoConatiner.addView(pointNameText, 1, layoutParams);
pointInfoConatiner.addView(pointDateText, 2, layoutParams);
point = new ImageView(getActivity());
point.setImageDrawable(getResources().getDrawable(R.drawable.puntoon));
}
}
Anyone know how can I:
1-Quit the bottom border
2-Quit the line of the pink chart
3-The chart don't move when I touch the points
4- When I ask for the screen point why to many times the y value returns infinite
There used to be this bug in an older version of AChartEngine. I suggest you update to 1.1.0.
Also, please note that the chart must have been already displayed when calling the method. If the chart didn't display on screen then there is no way to calculate that.

Categories

Resources