Aligning Elements in a CardView Programatically - java

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.

Related

How to programmatically create an object (i..: a textView) inside a CardView?

I want to make a newsletter app with the feature to make posts yourself.
I'm trying to makr a code for a button and I am stuck at the one moment. I don't know how to set a position for a new textView in the new cardView.
Here is a piece of code from MainActivity.java
package com.example.rame956.test;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ScrollView scrollView = new ScrollView(this);
}
//<...>
public void CreateNewPost(View view){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
CardView card = new CardView(this);
TextView text = new TextView(this);
ImageView image = new ImageView(this);
}
}
Sorry if it's a dumb qustion. I'm new in android developing.
For starters, I'd assume you would at least have a button inside your MainActivity which will trigger the process of creating a cardview. Therefore, to answer your question, I'll create a brand new card view programmatically from scratch. Take the elements which you need out of it i.e. textview, buttons and so on.
// Wiring in my 2 main aspects relativeLayout + Button
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
button = (Button) findViewById(R.id.btn);
//my trigger but in your case, it can be anything
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CardView card = new CardView(mContext);
// Set the CardView layoutParams
LayoutParams layoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
card.setLayoutParams(layoutParams );
// Setting different attributes
card.setRadius(9);
card.setContentPadding(15, 15, 15, 15);
card.setCardBackgroundColor(Color.parseColor("#FFC6D6C3"));
card.setMaxCardElevation(15);
card.setCardElevation(9);
// Initialize a new TextView to put in CardView
TextView tv = new TextView(mContext);
tv.setLayoutParams(layoutParams );
tv.setText("My CardView");
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
tv.setTextColor(Color.RED);
// Put the TextView inside CardView
card.addView(tv);
// Finally, add the CardView in root layout
relativeLayout.addView(card);
}
});
One thing to note here is the relativeLayout at the end of the function. You will need to have a parent layout in which you'll be placing your cardview. And of course, the attributes can be modified to your needs i.e. settext, backgroundcolour and so on.
If you simply want to insert a TextView to a pre-existing CardView in your xml. It'll be the same concept.
card = (CardView)findViewById(R.id.cardView);
//generate your textview as above....
card.addView(textView);

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.

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.

Creating relative layout (programmatically) with lot of fields

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);
}
}

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