Creating relative layout (programmatically) with lot of fields - java

I am trying to create a Relative Layout with java. I would insert logo on TOP, sharing on FOOTER and some info on middle.
For now, all components are getting on FOOTER, even if I pass the parameters to the header is on top.
My java code is:
package com.clubee.vote;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ResultadoFalho extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultadofalho);
Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(),R.drawable.bkg_app);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sharing);
RelativeLayout layoutLogo = (RelativeLayout) findViewById(R.id.ibresultadoFalho);
RelativeLayout.LayoutParams paramsLogo = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView bkgLogo = new ImageView(this);
bkgLogo.setLayoutParams(paramsLogo);
bkgLogo.setImageBitmap(bitmapTop);
layoutLogo.setGravity(Gravity.TOP| Gravity.CENTER_VERTICAL);
layoutLogo.addView(bkgLogo);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.ibresultadoFalho);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageButton sharingButton = new ImageButton(this);
sharingButton.setLayoutParams(params);
sharingButton.setImageBitmap(bitmap);
layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.BOTTOM);
layout.addView(sharingButton);
sharingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareIt();
}
});
}
private void shareIt() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Eu votei! E você, já opinou sobre a atual gestão da presidente do Brasil?";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Vote, Opine, Compartilhe");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Compartilhar"));
}
}
My activity xml is simple...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ibresultadoFalho"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#fffcfffa">
</RelativeLayout>

You need to use RelativeLayout.LayoutParams.
also checkout these other questions on SO,
How to align view elements in Relativelayout dynamically through
code in Android?
create dyanamic rule

EDITED:
I type the param this.addContentView(layout, lp); and now it works.
tks a lot 4 help.
After modify the first code, now the return is a white screen.
I pulled out some parts of the original code, so I would see better what was doing (right or wrong).
package com.clubee.vote;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class ResultadoFalho extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultadofalho);
RelativeLayout layout = new RelativeLayout(this);
Bitmap bitmapTop = BitmapFactory.decodeResource(getResources(),R.drawable.bkg_app);
ImageView bkgLogo = new ImageView(this);
bkgLogo.setId('1');
bkgLogo.setImageBitmap(bitmapTop);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(lp);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, bkgLogo.getId());
layout.addView(bkgLogo);
}
}

Related

Constraint Set dont work

my problem is, that I have a constraint set, which dont work. I have already tried a lot, but nothing worked... The button and the text are at the left side and the text is behind the button.
Here is a screenshot from the result at the moment
I want that the button is at the right side of the grey box and the text at the left top. Is this possible with only code?
package com.example.sbt_local.ticketui;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class MainActivity extends Activity {
private LinearLayout lLayout;
private ConstraintLayout cLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = this;
lLayout = new LinearLayout(context.getApplicationContext());
lLayout.setOrientation(LinearLayout.VERTICAL);
cLayout = new ConstraintLayout(context.getApplicationContext());
cLayout.setBackgroundColor(Color.parseColor("#FFEDEDED"));
cLayout.setPadding(4,4,4,4);
cLayout.setId(View.generateViewId());
ConstraintSet set = new ConstraintSet();
set.clone(cLayout);
Button cButton = new Button(context.getApplicationContext());
cButton.setText(">");
cButton.setLayoutParams(new RelativeLayout.LayoutParams(135, ViewGroup.LayoutParams.MATCH_PARENT));
cButton.setId(View.generateViewId());
set.connect(cButton.getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,0);
set.constrainHeight(cButton.getId(), 200);
set.applyTo(cLayout);
TextView tv_startDate = new TextView(context.getApplicationContext());
DateFormat df = new SimpleDateFormat("HH:mm dd.MM.yyyy");
tv_startDate.setText("Test");
tv_startDate.setId(View.generateViewId());
// Constraint Set
System.out.println("Layout ID: " + cLayout.getId());
System.out.println("Button ID: " + cButton.getId());
// Add Elements to Layout
cLayout.addView(cButton);
cLayout.addView(tv_startDate);
// Add Ticket to Layout List
TextView spacer = new TextView(context.getApplicationContext());
spacer.setTextSize(4); // Spacer Size
lLayout.addView(cLayout);
lLayout.addView(spacer);
LinearLayout llLayout = (LinearLayout) findViewById(R.id.layout);
llLayout.addView(lLayout);
}
}
Put this line:
set.applyTo(cLayout);
after the cButton has been added into cLayout:
cLayout.addView(cButton);
cLayout.addView(tv_startDate);
set.applyTo(cLayout);
because before cButton has been added into cLayout, its ConstraintSet.PARENT_ID is undefined.

Aligning Elements in a CardView Programatically

I'm working on a custom form activity that gives all elements their own CardView. When I add elements to a LinearLayout and add that to the CardView it works just fine, but when I try to arrange them in a RelativeLayout they don't seem to go where I want them. Here is a picture that shows the bug: Screenshot. The top is the error I'm getting, the bottom is what I'm trying to get it to look like.
Here's my current code:
package com.cpjd.roblu.activities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.cpjd.roblu.R;
import java.util.ArrayList;
public class TeamViewer extends Activity {
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
// adapters
LinearLayout layout;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_team_viewer);
layout = (LinearLayout) findViewById(R.id.team_viewer_cards);
addEditText();
addEditText();
addEditText();
addEditText();
addBoolean();
}
private void addBoolean() {
RadioGroup group = new RadioGroup(this);
RadioButton b = new RadioButton(this);
b.setText("Yes");
RadioButton b2 = new RadioButton(this);
b2.setText("No");
group.addView(b);
group.addView(b2);
TextView t = new TextView(this);
t.setText("Boolean");
RelativeLayout layout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
group.setLayoutParams(params);
layout.addView(t);
layout.addView(group);
addCard(layout);
}
private void addCard(View layout) {
CardView card = new CardView(getApplicationContext());
card.setLayoutParams(params);
card.setRadius(0);
card.setContentPadding(15, 15, 15, 15);
card.setUseCompatPadding(true);
card.setCardBackgroundColor(Color.DKGRAY);
card.setCardElevation(5);
card.addView(layout);
this.layout.addView(card);
}
}
In the LayoutParams you specified for the group, arguments should be flipped (first constructor argument is width, second - height, not the opposite):
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
Otherwise group takes full width of the parent and any horizontal alignment doesn't make any sense. Also try to avoid using getApplicationContext() when creating the views, because otherwise you get theme from the app, which may differ from the one you are using in Activity.
And the last: specify LayoutParams for all the views you create in runtime as well. For example, for the layout:
layout.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
Keep in mind, that LayoutParams is mandatory piece of information for every view. If not specified, then view will use the default one.

How to code Relative layout in java, instead of xml?

I want to run the app by using Java code instead of XML files.
The app is not working on my phone/emulator and crashing every time.
The code looks like this:
package com.nikhil.relativelayoutjavacode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
RelativeLayout main;
EditText userNameValue, passwordValue;
TextView message, userName, password;
LayoutParams messageDimensions;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessageTextView();
main.addView(message, messageDimensions);
setContentView(main);
}
private void init() {
// TODO Auto-generated method stub
main = new RelativeLayout(this);
LayoutParams mainDimensions = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
main.setLayoutParams(mainDimensions);
userNameValue = new EditText(this);
passwordValue = new EditText(this);
message = new TextView(this);
userName = new TextView(this);
password = new TextView(this);
login = new Button(this);
}
private void createMessageTextView() {
LayoutParams messageDimensions = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
messageDimensions.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
message.setText("Please Login First");
message.setLayoutParams(messageDimensions);
}
}
Here:
main.addView(message, messageDimensions);
messageDimensions is null because creating new object of LayoutParams with name messageDimensions in createMessageTextView() method instead of using messageDimensions object which is declared at class level.
So, use :
messageDimensions = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
messageDimensions.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
in createMessageTextView() method.

Trying to make a Dialog on click

I'm trying to make an help Dialog which provides some helpful tips to the users of my app. The tips should be in an #string resource to handle language issues. The dialog should pop up on click and the text in it should be scrollable. My current implementation fails to meet such requirements. Here is the code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import ch.OptiLab.visuscontroll.R;
public class MainActivity extends Activity implements OnClickListener {
TextView textView;
Button buttonende;
Button tipps;
Button btn1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
tipps = (Button) findViewById(R.id.tipps);
btn1 = (Button) findViewById(R.id.buttonSTART);
buttonende = (Button) findViewById(R.id.buttonende);
btn1.setOnClickListener(this);
tipps.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder (MainActivity.this.getActivity());
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
}
});
Change your code to
(...)
AlertDialog dialog = builder.create();
dialog.show(); //Do not forget this line
Also, make sure to correctly initialize builder:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

Add a Button dynamically to a LinearLayout in Android

I am working on a project that needs to add buttons dynamically. But whenever I run my application the application force closes. I've learned that the problem is when I try to add buttons.
package com.Feras.TestProject;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
public class TestProject extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AddAll();
// Set Text for the button in the Old Testament
}
public void AddAll() {
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout1);
Button btn = new Button(this);
btn.setText("MyButton");
linearLayout.addView(btn);
}
}
try like this:
linearLayout.addView(
btn,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)
);
there will only occure an error if linearLayout is null, ensure that layout1 is a valid Item of R.layout.main
Try the following in your custom activity class:
this.addContentView(call,
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

Categories