Constraint Set dont work - java

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.

Related

Further guidance with a Spinner

after testing out examples given here and here, I thought I would be able to add a score-point if the user selected the correct drop-down item. (I'm making a simple quiz app that toasts the final score).
Obviously this is too advanced for me, but I really don't want to give up and wondered if anyone might have any idea as to what I'm doing wrong please?
Here is how I have it set out in the MainActivity.java, with my failed attempts of implementing a way of checking the selected item stripped out:
First I set out the questions:
package com.example.android.arabic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.android.arabic.Nature.Nature;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
int arabicScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add emoji Q1
TextView q1 = findViewById(R.id.Q1_question);
q1.setText(Nature.HONEY_BEE);
// add emoji A2_option1
TextView qa2Option1 = findViewById(R.id.A2_option1);
qa2Option1.setText(Nature.GOAT);
// add emoji A2_option2
TextView qa2Option2 = findViewById(R.id.A2_option2);
qa2Option2.setText(Nature.BIRD);
// add emoji A2_option3
TextView qa2Option3 = findViewById(R.id.A2_option3);
qa2Option3.setText(Nature.HORSE);
//Q3 audio
Button q3Sound = this.findViewById(R.id.Q3_sound);
final MediaPlayer q3 = MediaPlayer.create(this, R.raw.camel);
q3Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q3.start();
}
});
// add emoji Q4_question
TextView q4 = findViewById(R.id.Q4_question);
q4.setText(Nature.ANT);
// Start of spinner Q4
Spinner a4 = findViewById(R.id.A4);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this,
R.array.a4_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
a4.setAdapter(adapter);
a4.setOnItemSelectedListener(this);
//Q5 audio
Button q5Sound = this.findViewById(R.id.Q5_sound);
final MediaPlayer q5 = MediaPlayer.create(this, R.raw.cow_bird);
q5Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q5.start();
}
});
//A5
// add emoji A5_option1
TextView qa5Option1 = findViewById(R.id.A5_option1);
qa5Option1.setText(Nature.COW);
// add emoji A5_option2
TextView qa5Option2 = findViewById(R.id.A5_option2);
qa5Option2.setText(Nature.PIG);
// add emoji A5_option3
TextView qa5Option3 = findViewById(R.id.A5_option3);
qa5Option3.setText(Nature.SNAKE);
// add emoji A5_option4
TextView qa5Option4 = findViewById(R.id.A5_option4);
qa5Option4.setText(Nature.BIRD);
}
//Display Result
public void results(View view){
// Check point for Q1
EditText a1EditText = findViewById(R.id.A1);
String a1Entry = a1EditText.getText().toString();
if (a1Entry.contains("نحلة")) {
arabicScore = arabicScore + 1;
}
// Check point for Q2
RadioButton a2Radio = findViewById(R.id.A2_option2);
boolean isa2RadioChecked = a2Radio.isChecked();
if (isa2RadioChecked){
arabicScore = arabicScore + 1;
}
// Check point for Q3
EditText a3EditText = findViewById(R.id.A3);
String a3Entry = a3EditText.getText().toString();
if (a3Entry.contains("جمل")) {
arabicScore = arabicScore + 1;
}
// Check point for Q4
Toast resultToast = Toast.makeText(this, "You got " + arabicScore + " of 7 questions right.", Toast.LENGTH_LONG);
resultToast.show();
}
Preview of layout
}
Thank you very much for your advice in advance! I've been stuck on this for months! :'D

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.

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

Android Spinner not showing up

Can anyone tell me why my spinners are not showing up? I'm doing an exercise and I don't understand why my spinners show no items at all. any suggestions?
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import java.util.*;
public class Length extends Activity{
private Spinner spi1,spi2,cmbOpciones;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.length);
//Spinner1
List<String> imperialunits = new ArrayList<String>();
imperialunits.add("inch");
imperialunits.add("foot");
imperialunits.add("yard");
imperialunits.add("mile");
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, imperialunits);
spi1=(Spinner)findViewById(R.id.spinner1);
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spi1.setAdapter(adaptador);
//Spinner2
final String[] SIunits =
new String[]{"km","m","cm"};
ArrayAdapter<String> adaptador2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, SIunits);
spi2 = (Spinner)findViewById(R.id.spinner2);
adaptador2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spi2.setAdapter(adaptador2);
//Spinner 3
final String[] datos = new String[]{"Elem1","Elem2","Elem3","Elem4","Elem5"};
ArrayAdapter<String> adaptador3 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, datos);
cmbOpciones = (Spinner)findViewById(R.id.CmbOpciones);
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cmbOpciones.setAdapter(adaptador3);
}
}
Your code to populate the Spinners looks fine (I think),maybe your problem is on your layout xml?, but why don't you try using an array of strings instead? like here, plus you get to use resource values, I personally think its better not creating stuff like that at runtime.
I tested your code and works perfectly. I agree, it must be something wrong in your xml file.

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