setBackgroundColor() appears not to work - android

I have some rather simple code. I go through each item within a layoutBIds array and set the color of the background accordingly.
setBackgroundColor works perfectly well on bidLayouts.
But when I call
BidDriverPrice.setBackgroundColor(getResources().getColor(R.color.Chartreuse));
It does not work for that view. I have tried setBackgroundResource and even single similar question from the first three pages of Google search result so I am sure I am missing something.
for (int i = 0; i < layoutBids.getChildCount(); i++) {
View v = layoutBids.getChildAt(i);
RelativeLayout bidLayouts = (RelativeLayout) v.findViewById(R.id.bidlayout);
final TextView BidDriverPrice = (TextView) v.findViewById(R.id.BidDriverPrice);
final TextView BidDriverMins = (TextView) v.findViewById(R.id.BidDriverPrice1);
if (rgxBidOffer.size() != 0) {
if (rgxBidOffer.get(Integer.parseInt(v.getTag().toString())).seconds > 0) {
bidLayouts.setBackgroundColor(ContextCompat.getColor(Variables.context, R.color.orange));
} else {
bidLayouts.setBackgroundColor(ContextCompat.getColor(Variables.context, R.color.White));
}
if (autoBidMode == Setting.AUTO_BID_MODE_CHEAPEST) {
for (TDriverBids rgxBids2 : rgxBidOffer) {
if (rgxBids2.amICheapest) {
autoBid = rgxBidOffer.get(Integer.parseInt(v.getTag().toString()));
BidDriverPrice.setBackgroundColor(getResources().getColor(R.color.Chartreuse));
} else {
BidDriverPrice.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
} else if (autoBidMode == Setting.AUTO_BID_MODE_NEAREST) {
for (TDriverBids rgxBids2 : rgxBidOffer) {
if (rgxBids2.amINearest) {
autoBid = rgxBidOffer.get(Integer.parseInt(v.getTag().toString()));
BidDriverMins.setBackgroundColor(getResources().getColor(R.color.Chartreuse));
} else {
BidDriverMins.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
}
}
}

you could try calling setContentView(R.layout.layout_name);
after you set the background color.

Related

How to simply save image to photo gallery

I'm playing with a drawing activity in Java converted/decompiled from this Kotlin sample.
I'm simplifying its functionalities and, as it is now, it allows me to click on "Save" button and a preview pops up with a text saying "Saved!", but I'd like to know what needs to be done to simply throw the resulting image to the Android photo gallery anytime the button is clicked (let's say, after saved, the image must become a standalone picture inside the camera gallery).
It seems it has to do with FileOutputStream/Bitmap.CompressFormat/MediaStore.Images
and I can foresee some difficulties in terms of naming files in a way they don't overwrite and I'm reading a lot of answers around here, but I still didn't get the logic so any idea is appreciated.
It's the first time I'm trying to do something similar so I'm sort of lost and I come here to ask for some directions.
Here is the single activity:
public final class SampleActivity extends AppCompatActivity implements OnSeekBarChangeListener, OnClickListener {
private HashMap _$_findViewCache;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_sample);
(this._$_findCachedViewById(id.close)).setOnClickListener(this);
(this._$_findCachedViewById(id.save)).setOnClickListener(this);
(this._$_findCachedViewById(id.undo)).setOnClickListener(this);
(this._$_findCachedViewById(id.clear)).setOnClickListener(this);
((SeekBar)this._$_findCachedViewById(id.red)).setOnSeekBarChangeListener(this);
((SeekBar)this._$_findCachedViewById(id.green)).setOnSeekBarChangeListener(this);
((SeekBar)this._$_findCachedViewById(id.blue)).setOnSeekBarChangeListener(this);
((SeekBar)this._$_findCachedViewById(id.width)).setOnSeekBarChangeListener(this);
}
public void onProgressChanged(#Nullable SeekBar seekBar, int progress, boolean fromUser) {
int var10000;
SeekBar var10001;
label58: {
label50: {
if (seekBar != null) {
var10000 = seekBar.getId();
var10001 = (SeekBar)this._$_findCachedViewById(id.red);
Intrinsics.checkExpressionValueIsNotNull(var10001, "red");
if (var10000 == var10001.getId()) {
break label50;
}
}
if (seekBar != null) {
var10000 = seekBar.getId();
var10001 = (SeekBar)this._$_findCachedViewById(id.green);
Intrinsics.checkExpressionValueIsNotNull(var10001, "green");
if (var10000 == var10001.getId()) {
break label50;
}
}
if (seekBar == null) {
break label58;
}
var10000 = seekBar.getId();
var10001 = (SeekBar)this._$_findCachedViewById(id.blue);
Intrinsics.checkExpressionValueIsNotNull(var10001, "blue");
if (var10000 != var10001.getId()) {
break label58;
}
}
SeekBar var8 = (SeekBar)this._$_findCachedViewById(id.red);
Intrinsics.checkExpressionValueIsNotNull(var8, "red");
int r = var8.getProgress();
var8 = (SeekBar)this._$_findCachedViewById(id.green);
Intrinsics.checkExpressionValueIsNotNull(var8, "green");
int g = var8.getProgress();
var8 = (SeekBar)this._$_findCachedViewById(id.blue);
Intrinsics.checkExpressionValueIsNotNull(var8, "blue");
int b = var8.getProgress();
int color = Color.argb(255, r, g, b);
((FingerPaintImageView)this._$_findCachedViewById(id.finger)).setStrokeColor(color);
(this._$_findCachedViewById(id.colorPreview)).setBackgroundColor(color);
return;
}
if (seekBar != null) {
var10000 = seekBar.getId();
var10001 = (SeekBar)this._$_findCachedViewById(id.width);
Intrinsics.checkExpressionValueIsNotNull(var10001, "width");
if (var10000 == var10001.getId()) {
((FingerPaintImageView)this._$_findCachedViewById(id.finger)).setStrokeWidth((float)progress);
}
}
}
public void onClick(#Nullable View v) {
if (Intrinsics.areEqual(v, this._$_findCachedViewById(id.undo))) {
((FingerPaintImageView)this._$_findCachedViewById(id.finger)).undo();
} else if (Intrinsics.areEqual(v, this._$_findCachedViewById(id.clear))) {
((FingerPaintImageView)this._$_findCachedViewById(id.finger)).clear();
} else if (Intrinsics.areEqual(v, this._$_findCachedViewById(id.close))) {
this.hidePreview();
} else if (Intrinsics.areEqual(v, this._$_findCachedViewById(id.save))) {
this.showPreview();
}
}
private final void showPreview() {
RelativeLayout var10000 = (RelativeLayout)this._$_findCachedViewById(id.previewContainer);
Intrinsics.checkExpressionValueIsNotNull(var10000, "previewContainer");
var10000.setVisibility(View.VISIBLE);
ImageView var1 = (ImageView)this._$_findCachedViewById(id.preview);
FingerPaintImageView var10001 = (FingerPaintImageView)this._$_findCachedViewById(id.finger);
Intrinsics.checkExpressionValueIsNotNull(var10001, "finger");
var1.setImageDrawable(var10001.getDrawable());
}
private final void hidePreview() {
RelativeLayout var10000 = (RelativeLayout)this._$_findCachedViewById(id.previewContainer);
Intrinsics.checkExpressionValueIsNotNull(var10000, "previewContainer");
var10000.setVisibility(View.GONE);
}
public void onStartTrackingTouch(#Nullable SeekBar seekBar) {
}
public void onStopTrackingTouch(#Nullable SeekBar seekBar) {
}
public void onBackPressed() {
RelativeLayout var10000 = (RelativeLayout)this._$_findCachedViewById(id.previewContainer);
Intrinsics.checkExpressionValueIsNotNull(var10000, "previewContainer");
if (var10000.getVisibility() == View.VISIBLE) {
this.hidePreview();
} else {
super.onBackPressed();
}
}
public View _$_findCachedViewById(int var1) {
if (this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View var2 = (View)this._$_findViewCache.get(var1);
if (var2 == null) {
var2 = this.findViewById(var1);
this._$_findViewCache.put(var1, var2);
}
return var2;
}
public void _$_clearFindViewByIdCache() {
if (this._$_findViewCache != null) {
this._$_findViewCache.clear();
}
}
}
Thanks in advance!
I was able to overcome this issue by taking another paint-like sample (a simpler one and in Java) called Android Drawable View.
This different sample and tips from previous answers available here on StackOverflow like this one and this other one were enough to put the project together so I'll try to explain how to.
First, you need to add permission to WRITE_EXTERNAL_STORAGE in your Manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Later, you just need to add a save button to your activity_main.xml:
<Button
android:id="#+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
Then, you initialize the button view onCreate and associate the new saveButton with a setOnClickListener and don't forget to request permission in realtime:
Button saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
drawableView.setEnabled(true);
}
else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{ Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
Bitmap bm = drawableView.obtainBitmap();
MediaStore.Images.Media.insertImage(getContentResolver(), bm, "title" , "description");
}
});
By using the method described above, I've been able to save a new media file inside a folder in the default gallery app on the emulator as you can see below:
However, it's still getting an unintended black background that I must overcome now, but I consider the initial issue solved as it answers my own original question.

Strange behavior of setColorFilter()

I have noticed a strange behavior of setColorFilter(). I have some buttons in my activity and when the user clicks on one of them, if a certain condition is true I want to set a green background to it, otherwise red. This doesn't work. However in another method, where there isn't any condition, the same statement works.
I have this problem only on ICS while on Lollipop all works well. I solved this by using a drawable to set the background, but I would like to understand why there is this problem.
First method:
private void setButtons() {
buttonList = new ArrayList<>();
/*buttons initialization*/
for (int i = 0; i < btnNumber; i++) {
buttonList.get(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
String buttonText = btn.getText().toString();
if (buttonText.equals(getAnswer())) {
//set background to GREEN
btn.getBackground().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.GREEN), PorterDuff.Mode.MULTIPLY);
}
else {
//set background to RED
btn.getBackground().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.RED), PorterDuff.Mode.MULTIPLY);
}
}
});
}
}
Second method in the same class:
private void revealAnswer() {
String answer = getAnswer();
for (int i = 0; i < btnNumber; i++) {
Button currentBtn = buttonList.get(i);
String currentText = (String) currentBtn.getText();
if (currentText.equals(answer)) {
//set background to GREEN
buttonList.get(i).getBackground().setColorFilter(ContextCompat.getColor(getApplicationContext(), R.color.GREEN), PorterDuff.Mode.MULTIPLY);
break;
}
}
}

smoosh 4 similar methods into 1 method

finishing up an android app, I have four methods each pertaining to their respective buttons. each is a color. if one is pressed, and its the correct color being told to be pressed it gets a +point, else it gets a -point.
these are the 4 methods im trying to combine into one, though I am having trouble figuring out that if i did, then I wouldnt have a way to to assign negative points. I was thinking that if i did like if blue, add points, else if teal add points etc... but this approach takes away from the fact that if they were told to press blue and pressed teal then it wouldnt register to add a -point.
here is the code:
public void blue_pressed(View view) {
correct = (TextView) findViewById(R.id.right);
incorrect = (TextView) findViewById(R.id.wrong);
if (count != 0 && !(count >NUMBER_ROUNDS) && color == blue) {
cor++;
correct.setText(getString(R.string.num_cor, cor));
} else {
inc++;
incorrect.setText(getString(R.string.num_inc, inc));
}
start_pressed(view);
}
public void teal_pressed(View view) {
correct = (TextView) findViewById(R.id.right);
incorrect = (TextView) findViewById(R.id.wrong);
if (count != 0 && !(count > NUMBER_ROUNDS) && color == teal) {
cor++;
correct.setText(getString(R.string.num_cor, cor));
} else {
inc++;
incorrect.setText(getString(R.string.num_inc, inc));
}
start_pressed(view);
}
public void purp_pressed(View view) {
correct = (TextView) findViewById(R.id.right);
incorrect = (TextView) findViewById(R.id.wrong);
if (count != 0 && !(count > NUMBER_ROUNDS) && color == purp) {
cor++;
correct.setText(getString(R.string.num_cor, cor));
} else {
inc++;
incorrect.setText(getString(R.string.num_inc, inc));
}
start_pressed(view);
}
public void pink_pressed(View view) {
correct = (TextView) findViewById(R.id.right);
incorrect = (TextView) findViewById(R.id.wrong);
if (count != 0 && !(count > NUMBER_ROUNDS) && color == pink) {
cor++;
correct.setText(getString(R.string.num_cor, cor));
} else {
inc++;
incorrect.setText(getString(R.string.num_inc, inc));
}
start_pressed(view);
}
thanks!
This question is really more about refactoring than Android.
You have 4 methods that differ only regarding the colour in the if statement. This means if you pass in the colour as a parameter, you would have only one method instead, and maintain only that. But you cannot change the signature of the "onClick" methods, so what to do? You create an additional private helper method that you call in all your four "onClick" methods.
In Eclipse you can extract easily the body of one of the "onClick" methods and refactor it into your helper method. Enter the shortcut: alt+command+M. Then change the signature of the extracted method manually to include an int parameter to compare color to. Finally you get...
private void buttonPressed(View view, int col){
correct = (TextView) findViewById(R.id.right);
incorrect = (TextView) findViewById(R.id.wrong);
if (count != 0 && !(count >NUMBER_ROUNDS) && color == col) {
cor++;
correct.setText(getString(R.string.num_cor, cor));
} else {
inc++;
incorrect.setText(getString(R.string.num_inc, inc));
}
start_pressed(view);
}
public void blue_pressed(View view) {
buttonPressed(view, blue);
}
public void teal_pressed(View view) {
buttonPressed(view, teal);
}
public void purp_pressed(View view) {
buttonPressed(view, purp);
}
public void pink_pressed(View view) {
buttonPressed(view, pink);
}

How to dynamically add components on a custom dialog?

Let's say I have a listView with some formulas like this:
((A * 2 + B * 3 + PF * 5) / 10)
When I click on it I would like to change the letters to EditTexts, so I split this String then, if it is a letter I should replace it by an EditText, so, what should I use to make this happen? I mean, can I have an activity loaded on a "Dialog Style" window? Or I can make this work with Simple Dialog?
I've tried this, but it gets error when adding the view(NullPointerException)
lsView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> aView, View view,
int i, long l) {
Dialog dialogFormula = new Dialog(NotasActivity.this); //"Parent" activity
dialogFormula.setTitle("Title");
LinearLayout layout = (LinearLayout)findViewById(R.id.DialogLayout);
String[] lines = materias.get(i).getFormula().split(" ");
for (String s : lines) {
if (s.compareTo("PARTIC") == 0) {
EditText edtPartic = new EditText(dialogFormula.getContext));
layout.addView(edtPartic);
} else if (s.contains("A") && s.compareTo("A") != 0) {
} else if (s.compareTo("B") == 0) {
} else if (s.compareTo("C") == 0) {
} else if (s.compareTo("D") == 0) {
} else if (s.compareTo("E") == 0) {
} else if (s.compareTo("F") == 0) {
} else if (s.compareTo("G") == 0) {
} else if (s.compareTo("H") == 0) {
} else if (s.compareTo("I") == 0) {
} else if (s.compareTo("PF") == 0) {
}
}
dialogFormula.setContentView(layout);
return false;
}
});
dialog_formula.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/DialogLayout">
<TextView
android:id="#+id/txtMateriaDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/txtFormulaDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
I suggest you make a custom dialog class.
public class FormulaDialog extends Dialog {
public FormulaDialog(Context c) {
super(c);
setTitle("Title");
setContentView(R.layout.dialog_formula);
}
public void updateLayout(String[] lines) {
LinearLayout layout = (LinearLayout)findViewById(R.id.DialogLayout);
for (String s : lines) {
if (s.compareTo("PARTIC") == 0) {
EditText edtPartic = new EditText(dialogFormula.getContext));
layout.addView(edtPartic);
} else if (s.contains("A") && s.compareTo("A") != 0) {
} else if (s.compareTo("B") == 0) {
} else if (s.compareTo("C") == 0) {
} else if (s.compareTo("D") == 0) {
} else if (s.compareTo("E") == 0) {
} else if (s.compareTo("F") == 0) {
} else if (s.compareTo("G") == 0) {
} else if (s.compareTo("H") == 0) {
} else if (s.compareTo("I") == 0) {
} else if (s.compareTo("PF") == 0) {
}
}
}
}
Then in your Activity all you have to run is
String[] lines = materias.get(i).getFormula().split(" ");
FormulaDialog mFormulaDialog = new FormulaDialog(this);
mFormulaDialog.updateLayout(lines);
mFormulaDialog.show();
findViewById() only returns views in the XML passed to the current Activity's setContentView(), typically this is your main.xml for your first activity. Since DialogLayout is in a different XML, this line returns null:
LinearLayout layout = (LinearLayout)findViewById(R.id.DialogLayout);
You want to inflate dialog_formula.xml, modify it, and then pass this XML to your Dialog; like this:
View view = getLayoutInflater().inflate(R.layout.dialog_formula, null, false);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.DialogLayout);
// Add your new EditTexts here
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setView(view);
dialog = builder.create();
To parse your formula, I have two different recommendations:
Keep a count of user variables for each formula, rather than parse the same string over and over.
If you must parse, test your string like this:
if("ABCDEFGHIPF".contains(s))
// Add EditText
else if(s.contains("PARTIC"))
// Do something special
// The rest are numbers or symbols

Creating clickable linearlayout dynamically

I have to create LinearLayouts dinamically according to an Entity List. The Layouts are drawn without problems. My problem is when I try to know which Layout I have clicked, because always is referencing the last.
The code is something like this:
LinearLayout llProducts = FindViewById<LinearLayout>(Resource.Id.llProducts);
LinearLayout llNewProduct;
int i = 0;
foreach(Product p in productsList)
{
llNewProduct = new LinearLayout(this);
llNewProduct.Clickable = true;
llNewProduct.Id = i++;
TextView txtProduct = new TextView(this);
txtProduct.Text = p.Name;
llNewProduct.AddView(txtProduct);
llProducts.AddView(llNewProduct);
llNewProduct.Click += (sender, e)
{
//This always shows the last Id
Toast.MakeText(this, llNewProduct.Id.ToString(), ToastLength.Short).Show();
}
}
I appreciate some help. Thanks
You have to create Array of boolean sucg as boolean[] flag = new boolean[productList.length]. After this, you can set flag[i] = true when you set llNewProduct.Clickable = true; other set flag[i] =false;
After completion for each loop you can find out clicked lineanlayout with the help of this flag such as
for(int i=0;i<flag.length;i++){
if(flag[i]){
Log.v("TAG","Clicked linear layout");
}else{
Log.v("TAG","Not Clicked linear layout");
}
}
Use following code in foor loop
llNewProduct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(YouActivity.this, ""+v.getId(), Toast.LENGTH_SHORT).show();
}
});
you are using same reference for all added view, create different views in side loop
Try like this:
for(int i1 = 0; i1 < 3;i1++)
{
LinearLayout llNewProduct = new LinearLayout(this);
LayoutParams p = new LayoutParams(100, 100);
llNewProduct.setLayoutParams(p);
if(i1 == 0) llNewProduct.setBackgroundColor(Color.RED);
if(i1 == 1) llNewProduct.setBackgroundColor(Color.GREEN);
if(i1 == 2) llNewProduct.setBackgroundColor(Color.BLUE);
llNewProduct.setClickable(true);
llNewProduct.setId(i1);
llNewProduct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(CaptureImage.this, ""+v.getId(), Toast.LENGTH_SHORT).show();
}
});
ll1.addView(llNewProduct);
}
As I said on the last comment. The question is solved. Next code shows the id from layout clicked.
llNewProduct.Click += (sender, e)
{
LinearLayout ll = sender as LinearLayout;
Toast.MakeText(this, ll.Id.ToString(), ToastLength.Short).Show();
}

Categories

Resources