smoosh 4 similar methods into 1 method - android

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

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.

Android: Check alpha state in if

So i have a OnClickListner, in here i would like to check the alpha state of a vector img.
p1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (/*aplpa*/ == 1) { //<----- alpha here
if (array[0] == 'o') {
p1.setBackgroundResource(R.drawable.ic_red);
array[0] = 'x';
} else {
p1.setBackgroundResource(R.drawable.ic_green);
array[0] = 'o';
}
array[1] = 1;
p1.setAlpha(1);
}
}
});
You shouldn't make your logic depend on the visible state of the app. Instead you should have some variable in your app which is what you set the alpha to when needed, and which you can check when you want.

setBackgroundColor() appears not to work

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.

Android : change the background color of click on same button

I have one TextView in my application and want to change the Background color of the same TextView .When i click 1st time it would be red , click on same 2nd time it would be green and 3rd time click it would be blue color background by problematically.
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Drawable d = textType.getBackground();
Log.e("textType "," click !!! ");
if(d.getConstantState() == getResources().getDrawable(R.drawable.red_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.green_circle_shape);
}
if(d.getConstantState() == getResources().getDrawable(R.drawable.green_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.blue_circle_shape);
}
if(d.getConstantState() == getResources().getDrawable(R.drawable.blue_circle_shape).getConstantState())
{
textType.setBackgroundResource(R.drawable.red_circle_shape);
}
}
});
This cod is not working.Thanks to appropriate.
Create a global variable x initialize it with 0. Then code like this:
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(x<4)
{
x= x+1;
}
else{
x = 1;
}
if(x==1)
{
// red color
}
else if(x==2)
{
// blue color
}
else if(x==3)
{
// green color
}
}
});
Use the below code,
textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
private int mCounter = 0;
#Override
public void onClick(View v)
{
if (mCounter == 0)
v.setBackgroundResource(R.drawable.red_circle_shape);
else
if (mCounter == 1)
v.setBackgroundResource(R.drawable.green_circle_shape);
else
v.setBackgroundResource(R.drawable.blue_circle_shape);
mCounter++;
}
});
Try this;
Define a global Variable int type.
Inside your onClick(), increment the int Variable
use switch or if statement to change the color when the variable increases e.g.
If(variable == 1)
// change color to Blue
else if (variable == 2)
// change color to Yellow
Hi Use the following code to Change the Color. Paste these lines inside your textView Onclick. Variable count is a global variable.
if (count == 0)
txtView.setTextColor(colorcode1);
else if (count == 1)
txtView.setTextColor(colorcode2);
else
txtView.setTextColor(colorcode3);
count++;
if (count > 2)
count = 0;
Try below code
TextView textType = (TextView)findViewById(R.id.textRNG);
textType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(current)
{
case 1:
tv.setBackgroundColor(Color.parseColor("#00ff00"));
current = 2;
break;
case 2:
tv.setBackgroundColor(Color.parseColor("#0000ff"));
current = 3;
break;
case 3:
tv.setBackgroundColor(Color.parseColor("#ff0000"));
current = 1;
break;
default:
break;
}
}
});

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

Categories

Resources