Drawing a new view into a relative layout - android

We are writing a "dashboard" for a car. The code for calculating/drawing the speedometer was done separate from the rest of the code, and now I am trying to combine the two.
They both work separately, and with the speedometer view code in, the main portion of the UI is still functioning, I just can't see the speedometer.
I have it compiling, and there are no obvious errors. However, when the app is run, I don't see the speedometer showing up in the main view, even though I have added it using the addView method.
For Reference:
My code to create and add the view:
setContentView(R.layout.main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.CENTER_VERTICAL);
myView v = new myView(this);
v.setLayoutParams(lp);
relativeLayout.addView(v, lp);
The code for the myView class:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.View;
public class myView extends View {
private Paint mPaints;
private Paint textpaint;
private boolean mUseCenters;
private RectF mBigOval;
private float mStart;
private float mSweep;
public float SPEED_raw;
public int SPEED = 0; //initialized to 0 just for loop. Remove initialization when IF statement below is deleted
public static Bitmap gaugefront;
public static Bitmap gaugeback;
public myView(Context context) {
super(context);
mPaints = new Paint();
mPaints.setAntiAlias(true);
mPaints.setColor(Color.YELLOW);
textpaint = new Paint();
textpaint.setAntiAlias(true);
textpaint.setColor(Color.WHITE);
textpaint.setTextSize(150);
textpaint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
gaugefront = BitmapFactory.decodeResource(context.getResources(),R.drawable.gaugefront); //Load gaugefront.png
gaugeback = BitmapFactory.decodeResource(context.getResources(),R.drawable.gaugeback); //Load gaugeback.png
mUseCenters = true;
mBigOval = new RectF(400, 10, 880, 490); //left[x-coordinate],top[y-coordinate],right[x],bottom[y]
}
private void drawArcs(Canvas canvas, RectF oval, boolean useCenter, Paint paint) {
canvas.drawArc(oval, mStart, mSweep, useCenter, paint);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(myView.gaugeback, 400, 10, null); //draw gauge background, X coordinate:400, Y coordinate: 10
drawArcs(canvas, mBigOval, mUseCenters, mPaints);
//SPEED_raw = 70; //Raw float data from CCS. Uncomment when the IF statement below is deleted.
SPEED = Math.round(SPEED_raw); //SPEED integer. Units km/h - Top speed of 135. Used for digital readout
mStart = 90; //Start drawing from -90 degrees (Counter clockwise)
mSweep = SPEED_raw*2; //Draw stop point
if(SPEED >= 135){ //JUST FOR SHOW. Delete this for actual speedo
SPEED_raw = 0; // "
} // "
else // "
SPEED_raw += 0.5; // "
canvas.drawBitmap(myView.gaugefront, 400, 10, null); //draw gauge foreground, X coordinate:400, Y coordinate: 10
String speed_string = String.valueOf(SPEED); //Convert int SPEED to String for display
// while (speed_string.endsWith(".0") || speed_string.endsWith(".")){ //Erase trailing ".0" for float types. Don't need if SPEED is an int
// speed_string = (speed_string.substring(0, speed_string.length() - 1));
// }
canvas.drawText(speed_string, 640, 420, textpaint); //arguments: (string, x-coordinate, y-coordinate, paint)
invalidate();
}
}
Here's my XML File:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:keepScreenOn="true"
android:orientation="vertical" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/solarbg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/solarbg" />
</LinearLayout>
<ImageView
android:id="#+id/l_lamp"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_gravity="left"
android:src="#drawable/l_arrow_dim" />
<DigitalClock
android:id="#+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="#ffffff"
android:textSize="50dp" />
<ImageView
android:id="#+id/r_lamp"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/r_arrow_dim" />
<TextView
android:id="#+id/setAmps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="left"
android:text="#string/setAmps"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/setAmpsVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:layout_below = "#+id/setAmps"
android:layout_alignParentLeft="true"
android:maxEms = "5"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/setVelocity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/setAmps"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:gravity="right"
android:text="#string/setVelocity"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/setVelocityVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_below = "#+id/setVelocity"
android:layout_alignParentRight="true"
android:maxEms = "5"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/actVelocity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/setVelocityVal"
android:gravity="right"
android:text="#string/actVelocity"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/actVelocityVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below = "#+id/actVelocity"
android:layout_alignParentRight="true"
android:gravity="right"
android:maxEms = "5"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/busAmps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/setAmpsVal"
android:gravity="left"
android:text="#string/busAmps"
android:textColor="#ffffff"
android:textSize="30dp" /><TextView
android:id="#+id/busAmpsVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:layout_below = "#+id/busAmps"
android:maxEms = "5"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/powerVal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom = "true"
android:gravity="right"
android:textColor="#ffffff"
android:textSize="30dp" />
<TextView
android:id="#+id/power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_above = "#+id/powerVal"
android:gravity="left"
android:text="#string/power"
android:textColor="#ffffff"
android:textSize="30dp" />
<TableLayout
android:id="#+id/msgCenterLayout"
android:layout_width="600dp"
android:layout_height="200dp"
android:layout_alignParentBottom = "true"
android:layout_centerHorizontal = "true"
android:orientation = "vertical"
android:visibility = "invisible">
<ScrollView
android:id="#+id/messageCenterText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="left"
android:text="#string/busAmps"
android:textColor="#ffffff"
android:textSize="30dp" />
</TableLayout>
</RelativeLayout>
edit:
I'm using an XML file for the main layout, and trying to add this new view to a relativelayout inside that XML file.

Try writing
LayoutParams p = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT);
v.setLayoutParams(lp);
relativeLayout.addView(v);

Related

How to set margin programmatically in android for a textview inside linearlayout?

I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ScrollView mainScrollView;
LinearLayout scrollViewContainer;
ArrayList<String> stringArr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);
stringArr = new ArrayList<String>();
String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
"The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
"in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
" use of this constructor is unnecessary since Strings are immutable.";
for(int ii = 0; ii < 10; ii++){
if(ii%2 == 0) {
stringArr.add(str1);
}else{
stringArr.add(str2);
}
}
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
LinearLayoutCompat.LayoutParams textViewLayoutParams = new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
for(int ii = 0; ii < stringArr.size(); ii++){
TextView textView = new TextView(this);
textView.setTextSize(12f);
textView.setText(stringArr.get(ii));
textView.setLayoutParams(textViewLayoutParams);
textViewLayoutParams.setMargins(10,30,10,30);
textView.requestLayout();
scrollViewContainer.addView(textView);
}
}
}
Your problem is in using
LinearLayoutCompat.LayoutParams textViewLayoutParams = new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Instead use:
LinearLayout.LayoutParams textViewLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewLayoutParams.setMargins(10,30,10,30);
textView.setLayoutParams(textViewLayoutParams);
this could be the problem ... you were editing textViewLayoutParams AFTER you were setting it to a textView.setLayoutParams(textViewLayoutParams) ...
You are using LinearLayout so try to use LinearLayout.LayoutParams
`<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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="#fff"
tools:context="com.example.sheheryar.quicktransport.Signin">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="false">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="250dp"
android:layout_height="155dp"
android:id="#+id/imageView2"
android:background="#drawable/logo1"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40px">
<EditText
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textSize="15dp"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/editTextemail"
android:hint="Enter email"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<EditText
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textSize="15dp"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editTextpassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember Password"
android:textColor="#6b6b6b"
android:id="#+id/cbRemberPassword"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:checked="false" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign in"
android:id="#+id/buttonsigin"
android:textColor="#ffffff"
android:onClick="userlogin"
android:background="#drawable/button_styles1"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OR"
android:id="#+id/textView1"
android:textColor="#f99906"
android:textStyle="bold"
android:textSize="18dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create New Account"
android:id="#+id/textView"
android:textColor="#6b6b6b"
android:textSize="18dp"
android:layout_marginTop="5dp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</RelativeLayout>`
Check in XML file. Under resources > layouts. Set the margins.
Maybe this can help.

Can't make calculations using a mix of TextView and EditText

I'm currently making a very simple math game. In this math game I want the player to solve easy equations. It looks like this: 9 * __ = 45, the player then fill in the correct number to solve the equation and then presses a Correct-button. If correct scores are added to the player.
The empty space is an EditText and the others are TextViews. Because I use a mix of TextView & EditText I need somehow to make a convertion for the program to be able to read and calculate. I've been reading like crazy and tried all kinds of different methods without success. How should I do to get around this?
This is how my data looks like:
activity_play.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.laboration2.PlayActivity">
<TextView
android:id="#+id/textPlayMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textPlayNumber1"
android:layout_centerHorizontal="true"
android:text="#string/multiply"
android:textAlignment="textStart"
android:layout_gravity = "start"
android:textColor="#android:color/black"
android:textSize="40sp" />
<TextView
android:id="#+id/textPlayNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/textPlayScore"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textPlayScore"
android:layout_marginTop="48dp"
android:text="#string/number_1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/equal"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/editTextPlayNumber2"
android:layout_alignLeft="#+id/textPlayMultiply"
android:layout_alignStart="#+id/textPlayMultiply" />
<TextView
android:id="#+id/textPlayResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
android:text="#string/result_number3"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp"
android:layout_below="#+id/textPlayEqual"
android:layout_alignLeft="#+id/textPlayEqual"
android:layout_alignStart="#+id/textPlayEqual" />
<TextView
android:id="#+id/textPlayScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="31dp"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/score_0"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textColor="#android:color/black"
android:textSize="24sp"
android:layout_toLeftOf="#+id/answerButton" />
<Button
android:id="#+id/answerButton"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:background="#android:color/holo_orange_dark"
android:text="#string/button_result"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold"
android:layout_below="#+id/textPlayResult"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/editTextPlayNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayMultiply"
android:layout_alignBottom="#+id/textPlayMultiply"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:hint=" "
android:inputType="number"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textPlayLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textPlayScore"
android:layout_alignBottom="#+id/textPlayScore"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:text="#string/level_0"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</RelativeLayout>
.
PlayActivity.java
package com.example.android.laboration2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PlayActivity extends AppCompatActivity implements View.OnClickListener {
TextView textPlayNumber1;
EditText editTextPlayNumber2;
TextView textPlayResult;
TextView textPlayScore;
TextView textPlayLevel;
Button answerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
textPlayNumber1 = (TextView) findViewById(R.id.textPlayNumber1);
editTextPlayNumber2 = (EditText) findViewById(R.id.editTextPlayNumber2);
textPlayResult = (TextView) findViewById(R.id.textPlayResult);
textPlayScore = (TextView) findViewById(R.id.textPlayScore);
textPlayLevel = (TextView) findViewById(R.id.textPlayLevel);
answerButton = (Button) findViewById(R.id.answerButton);
answerButton.setOnClickListener(this);
}//onCreate ends here
#Override
public void onClick(View v) {
}//onClick ends here
}//PlayActivity ends here
You can do
int playNumberValue = Integer.getInteger(textPlayNumber1.getText().toString());
int userInputValue = Integer.getInteger(editTextPlayNumber2.getText().toString());
int result = Integer.getInteger(textPlayResult.getText().toString());
if(result == userInputValue+playNumberValue)
//win game
Your TextView and EditText all have String type values. You have to parse those value to Integer then calculate and show the result.
Here is the action onClick answer button-
int score = 0;
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.answerButton:
int playNum1 = Integer.parseInt(textPlayNumber1.getText().toString());
int playNum2 = Integer.parseInt(editTextPlayNumber2.getText().toString());
int playResult = Integer.parseInt(textPlayResult.getText().toString());
if(playNum1*playNum2 == playResult){
score++;
textPlayScore.setText(""+score);
}
break;
}
}
Hope this helps.

Programmatically draw lines between buttons on android

I am trying to create a tree graph based on user data. There is no library or anything to help and im just a beginner. I just created 8 image buttons and after the app calculates the data, it needs to draw lines between these nodes to connect them. I have no idea how to use canvas or drawline so any help would be much appreciated.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp"
android:id="#+id/nodesImages">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="1"
android:layout_margin="20dp"
android:id="#+id/node1"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="2"
android:id="#+id/node2"
android:layout_margin="20dp"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="5"
android:id="#+id/node5"
android:layout_margin="20dp"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="6"
android:id="#+id/node6"
android:layout_margin="20dp"
android:background="#drawable/node"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="3"
android:layout_margin="20dp"
android:id="#+id/node3"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="4"
android:id="#+id/node4"
android:layout_margin="20dp"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="7"
android:id="#+id/node7"
android:layout_margin="20dp"
android:background="#drawable/node"/>
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:text="8"
android:id="#+id/node8"
android:layout_margin="20dp"
android:background="#drawable/node"/>
![enter image description here][1]</LinearLayout>
Edit - DrawView Class
How can I use this DrawView class to add the lines?
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View
{
Paint paint = new Paint();
static int startX, startY, endX, endY;
public DrawView(Context context,int startX, int startY, int endX, int endY)
{
super(context);
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
paint.setColor(Color.BLACK);
}
public DrawView(Context context)
{
super(context);
paint.setColor(Color.BLACK);
}
#Override
public void onDraw(Canvas canvas)
{
canvas.drawLine(startX, startY, endX, endY,paint);
}
}
Edit 2:
This is not working for some reason:
LinearLayout myLayout = (LinearLayout) findViewById(R.id.nodesImages);
DrawView drawView = new DrawView(getApplicationContext(),(int)node1.getX(),(int)node1.getY(),(int)node2.getX(),(int)node2.getY());
myLayout.addView(drawView);
Edit 3
There are so many libraries for creating complex graphs (line,bar,scatter,etc) . Why can't somebody create a library for tree graphs???? seems easy for those people!!!
based on your provide width and height of your button in layout. I use translation to do that. See the below code and the ugly Image for explain ##!
LinearLayout nodesImages = (LinearLayout) findViewById(R.id.nodesImages);
View v = new View(this); //this, because I write this code in the Activity class
//yah, try to understand values 20, 30,...
v.setLayoutParams(new ViewGroup.LayoutParams(dpToPx(20+20),dpToPx(2)));
v.setBackgroundColor(Color.BLACK);
nodesImages.addView(v);
v.setTranslationY(-dpToPx(30+20+20)-dpToPx(20+30/2));
v.setTranslationX(dpToPx(20+30));
with:
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
Ugly Image for explain:
UPDATE get location of view:
final LinearLayout nodesImages = (LinearLayout) findViewById(R.id.nodesImages);
//using addOnGlobalLayoutListener to make sure layout is happened.
nodesImages.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//Remove the listener before proceeding
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
nodesImages.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
nodesImages.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
Button node1 = (Button)findViewById(R.id.node1);
int[] loc1 = new int[2];
node1.getLocationInWindow(loc1);//loc1[0] is x and loc1[1] is y
//for more information about this method, in Android Studio, just right-click -> Go To -> Declaration
Button node2 = (Button)findViewById(R.id.node2);
int[] loc2 = new int[2];
node2.getLocationInWindow(loc2);
View v = new View(getApplication());
v.setLayoutParams(new ViewGroup.LayoutParams(loc2[0]-loc1[0]-node1.getWidth(),dpToPx(2)));//dpToPx(20 + 20), dpToPx(2)));
v.setBackgroundColor(Color.BLACK);
nodesImages.addView(v);
v.setTranslationY(-dpToPx(30+20+20)-dpToPx(20+30/2));
v.setTranslationX(dpToPx(20+30));
}
}
);
Psst... Just do it in XML
<View
android:layout_height="1dp"
android:layout_width="match_parent"
android:background="#android:color/black"/>

Android Add view to linearlayout in relativeLayout on button click

help me solve my problem. There is a main layout RelativeLayout it is Linearlayout where I want to programmatically add view. Here is my code.
public class GenBarCodeActivity extends Activity {
BarCodeView Barview = null;
LinearLayout.LayoutParams layoutParams;
LinearLayout ll;
RelativeLayout rl;
Button getBarCode;
private static final int ID = 34646456;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
getBarCode = (Button)findViewById(R.id.btnGetBarCode);
getBarCode.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ll = (LinearLayout)findViewById(R.id.linearCodeView);
EANTEXT = edBarText.getText().toString();
ImageView old = (ImageView) ll.findViewById(ID);
if (old != null) {
((LinearLayout) old.getParent()).removeViewInLayout(old);
}
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(Barview, layoutParams);
rl.invalidate();
}
});
fillLinear();
setBarCode();
}
private void fillLinear(){
rl = (RelativeLayout)findViewById(R.id.layout_barcode);
ll = (LinearLayout)findViewById(R.id.linearCodeView);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageView imBar = new ImageView(this);
Bitmap imbitmap = BitmapFactory.decodeResource(getResources(), R.drawable.barcode);
imBar.setLayoutParams(layoutParams);
imBar.setImageBitmap(imbitmap);
imBar.setId(ID);
ll.setBackgroundColor(Color.TRANSPARENT);
ll.addView(imBar);
}
private void setBarCode(){
Barview = new BarCodeView(GenBarCodeActivity.this);
Barview.setBarCodeNum(0);
}
}
This is my View
public class BarCodeView extends View {
private static int numcode = 0;
private static String codedata = null;
public BarCodeView(Context context) {
super(context);
}
public void setBarCodeText(String text){
this.codedata = text;
}
public String getBarCodeText(){
return this.codedata;
}
public void setBarCodeNum(int num){
this.numcode = num;
}
public int getBarCodeNum(){
return this.numcode;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
switch (numcode) {
// ean 13
case 0:
try{
showEAN13(canvas);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
private static void showEAN13(Canvas canvas) throws Exception {
EAN13 barcode = new EAN13();
/*
EAN 13 Valid data char set:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (Digits)
EAN 13 Valid data length: 12 digits only, excluding the last checksum digit
*/
barcode.setData(codedata);
// for EAN13 with supplement data (2 or 5 digits)
/*
barcode.setSupData("12");
// supplement bar height vs bar height ratio
barcode.setSupHeight(0.8f);
// space between barcode and supplement barcode (in pixel)
barcode.setSupSpace(15);
*/
// Unit of Measure, pixel, cm, or inch
barcode.setUom(IBarcode.UOM_PIXEL);
// barcode bar module width (X) in pixel
barcode.setX(2f);
// barcode bar module height (Y) in pixel
barcode.setY(90f);
// barcode image margins
barcode.setLeftMargin(10f);
barcode.setRightMargin(10f);
barcode.setTopMargin(10f);
barcode.setBottomMargin(10f);
// barcode image resolution in dpi
barcode.setResolution(72);
// disply barcode encoding data below the barcode
barcode.setShowText(true);
// barcode encoding data font style
barcode.setTextFont(new AndroidFont("Arial", Typeface.NORMAL, 10));
// space between barcode and barcode encoding data
barcode.setTextMargin(6);
barcode.setTextColor(AndroidColor.black);
// barcode bar color and background color in Android device
barcode.setForeColor(AndroidColor.black);
barcode.setBackColor(AndroidColor.white);
/*
specify your barcode drawing area
*/
RectF bounds = new RectF(120, 120, 0, 0);
barcode.drawBarcode(canvas, bounds);
}
}
here is my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_barcode"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0e0a2"
android:orientation="vertical" >
<ImageView
android:id="#+id/closeBarCode"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/txtInfo"
android:layout_marginRight="3dp"
android:src="#drawable/delete" />
<TextView
android:id="#+id/txtInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="3dp"
android:layout_marginTop="3dp"
android:text="#string/barcode_title"
android:textColor="#000"
android:textSize="20dip" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/closeBarCode" >
<TextView
android:id="#+id/txtEAN"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/barcode_ean"
android:textColor="#000"
android:textSize="20dip" />
<Spinner
android:id="#+id/spEAN"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtInfo"
android:layout_below="#+id/linearLayout1" >
<TextView
android:id="#+id/txtCodeColor"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/barcode_color"
android:textColor="#000"
android:textSize="20dip" />
<Spinner
android:id="#+id/spCodeColor"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout2"
android:layout_below="#+id/linearLayout2" >
<TextView
android:id="#+id/txtCodeBackColor"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/barcode_back_color"
android:textColor="#000"
android:textSize="20dip" />
<Spinner
android:id="#+id/spCodeBackColor"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout3" >
<TextView
android:id="#+id/txtCodePosition"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/barcode_position"
android:textColor="#000"
android:textSize="20dip" />
<Spinner
android:id="#+id/spCodePosition"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearCodeView"
android:layout_width="300dip"
android:layout_height="200dip"
android:layout_below="#+id/edBarCode"
android:layout_marginRight="45dp"
android:layout_marginTop="25dip"
android:layout_toLeftOf="#+id/closeBarCode"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="#+id/btnSetBarCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnGetBarCode"
android:layout_alignBottom="#+id/btnGetBarCode"
android:layout_toLeftOf="#+id/closeBarCode"
android:text="#string/set_code" />
<Button
android:id="#+id/btnGetBarCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="31dp"
android:text="#string/get_code" />
<EditText
android:id="#+id/edBarCode"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearCodeView"
android:layout_alignRight="#+id/linearCodeView"
android:layout_below="#+id/txtCodeText"
android:layout_marginTop="23dp"
android:ems="10" />
<TextView
android:id="#+id/txtCodeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/edBarCode"
android:layout_below="#+id/txtInfo"
android:layout_marginRight="86dp"
android:text="#string/code_text"
android:textColor="#000"
android:textSize="20dip" />
</RelativeLayout>
I need to Linearlayout "#+id/linearCodeView" insert my BarCodeView.
View is not visible after adding LinearLayout.
RelativeLayout.LayoutParams paramsBottom = new RelativeLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(ll, paramsBottom); //add linearlayout in relativelayout
Edit:-
LinearLayout.LayoutParams paramsBottom2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(Barview, paramsBottom2);//add Barview in linearlayout
OR
RelativeLayout.LayoutParams paramsBottom2 = new RelativeLayout.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
rl.addView(Barview, paramsBottom2);//add Barview in relativelayout

Adjust view width and height to 50%

I'm creating a gallery with custom adapter (a relative layout in witch i place an imageview as a thumbnail, a textview as Name and other staff).
The gallery displays in fullscreen perfectly, but this is not what i want.. i want the custom relative layout to be scaled to 50% in height and width relatively to the screen size. I tried this :
gallery.getLayoutParams().width = relativelayout.getWidth() / 2;
gallery.getLayoutParams().height = relativelayout.getHeight() / 2;
This was a wrong try, it just set the height and width to the correct size without scaling the content.
This is the original view :
This is what i've expected :
And this is what i've got :
This is the layout Cover :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/ivTourCover"
android:layout_width="640dp"
android:layout_height="240dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/croppedstopgallery_f45d88e4_7864_4dbc_9123_ad7953d8724a" />
<ImageButton
android:id="#+id/ivHorizontalLine"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/tvTourName"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="0dp"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/horizontal_line" />
<TextView
android:id="#+id/tvAuthorName"
style="#style/Cover.AuthorName"
android:layout_width="fill_parent"
android:layout_height="19dp"
android:layout_alignTop="#+id/ivAuthorThumbnail"
android:layout_marginLeft="12dp"
android:layout_marginRight="17dp"
android:layout_toLeftOf="#+id/ivGo"
android:layout_toRightOf="#+id/ivAuthorThumbnail"
android:text="Anna Greenleaf" />
<ImageView
android:id="#+id/ivAuthorThumbnail"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignLeft="#+id/ivHorizontalLine"
android:layout_below="#+id/ivHorizontalLine"
android:layout_marginTop="20dp"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/croppedstopgallery_f45d88e4_7864_4dbc_9123_ad7953d8724a" />
<ImageView
android:id="#+id/ivGo"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignRight="#+id/ivHorizontalLine"
android:layout_alignTop="#+id/tvAuthorName"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/tour_cover_go" />
<TextView
android:id="#+id/tvAuthorDescription"
style="#style/Cover.AuthorDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvAuthorName"
android:layout_alignRight="#+id/tvAuthorName"
android:layout_below="#+id/tvAuthorName"
android:text="London native and London over!" />
<SurfaceView
android:id="#+id/svFooter"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:background="#color/CoverFooter" />
<TextView
android:id="#+id/tvFooterText"
style="#style/Cover.FooterText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/svFooter"
android:layout_alignBottom="#+id/svFooter"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:text="Individual" />
<com.example.zipdownload.utilities.ui.AutoResizeTextView
android:id="#+id/tvTourName"
style="#style/Cover.TourName"
android:layout_width="wrap_content"
android:layout_height="79dp"
android:layout_below="#+id/ivTourCover"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="15dp"
android:gravity="center|top"
android:text="Beautiful London in Winston Churchill&apos;s footsteps" />
</RelativeLayout>
The View Gallery :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlGallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Gallery" >
<Gallery
android:id="#+id/gCoverflow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="top" />
</RelativeLayout>
And the Activity Gallery :
public class Gallery extends Activity {
private android.widget.Gallery gCoverflow;
private RelativeLayout rlGallery;
private CoverAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
rlGallery = (RelativeLayout) findViewById(R.id.rlGallery);
adapter = new CoverAdapter(this);
gCoverflow = (android.widget.Gallery) findViewById(R.id.gCoverflow);
gCoverflow.setAdapter(adapter);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
gCoverflow.getLayoutParams().width = rlGallery.getWidth() / 2;
gCoverflow.getLayoutParams().height = rlGallery.getHeight() / 2;
}
}
You can try to use ScaleAnimation but in this case touch events will work incorrect:
final ScaleAnimation animation = new ScaleAnimation (
1f, 0.5f, 1f, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
);
final LayoutAnimationController controller = new LayoutAnimationController(animation);
animation.setDuration(0);
animation.setFillAfter(true);
gCoverflow.setLayoutAnimation(controller);
This code should be added in onCreate method.
I found it guys, is stead of :
gCoverflow.getLayoutParams().width = rlGallery.getWidth() / 2;
gCoverflow.getLayoutParams().height = rlGallery.getHeight() / 2;
I user this :
gCoverflow.setScaleX((float) 0.5);
gCoverflow.setScaleY((float) 0.5);

Categories

Resources