How to dynamically add components on a custom dialog? - android

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

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.

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.

Spinner.setOnLongClickListener() not working in Android

In one of my Android's activity LongClickListener() is not working with Spinner. I have made spinner programmatically in a method which is called when Api gets hit in onCreate(). I want to enable the tdpidSpinner when it is longclicked by user.
Here's the method:
public boolean setTdpId(ArrayList<String> tdpList) {
try {
tdpIdList = tdpList;
runOnUiThread(new Runnable() {
#Override
public void run() {
tdpidSpinner = new Spinner(Activity_Settings.this);
TableRow.LayoutParams tdpid_spinner_params = new
TableRow.LayoutParams(
0, LayoutParams.WRAP_CONTENT, 3f);
tdpidSpinner.setLayoutParams(tdpid_spinner_params);
rowTdpid.addView(tdpidSpinner);
tdpidSpinner.setPrompt("Select TdpId");
tdpidSpinner.setLongClickable(true);
tdpidSpinner.setClickable(true);
if (tdpIdList.size() > 0) {
ArrayAdapter<String> spinnerAdapter = new
ArrayAdapter<String>(
Activity_Settings.this,
android.R.layout.simple_spinner_item,
tdpIdList);
tdpidSpinner.setAdapter(spinnerAdapter);
String tdpid = mActivity.getSharedPreferences(
Utility.PREFERENCE_NAME, Context.MODE_PRIVATE)
.getString(Utility.TDPID, "");
// if(tdpid!=null || tdpid!=""){
if (tdpid != "") {
int spinnerPosition = spinnerAdapter
.getPosition(tdpid);
tdpidSpinner.setSelection(spinnerPosition);
tdpidSpinner.setEnabled(false);
}
tdpidSpinner.setOnLongClickListener(new
View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
tdpidSpinner.setEnabled(true);
return true;
}
});
}
}
Long click event will be dispatched to item view of spinner,not spinner.So if you want add longclicklistener,add it to its item view.
If your Spinner is disabled (tdpidSpinner.setEnabled(false);), it won't respond to touch events.
From the onTouchEvent function of View (see here):
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}

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 Handle two listviews in one activity?

In my application,im using two listviews and both are not showing simultaneously.But im using the same "custom adapter class".But it is showing different results while implementing pagination.Pagination works well in the first listview which loads initially.But when i click another listview to show the results,it is not working
My Problem: How to implement pagination in both of these listviews effectively?Is it better to use two different custom adapter class?
Here the sample code which i done for pagination------
btnNext.setVisibility(View.VISIBLE);
TotalPages = TotalPages + 1;
if (pagenum == 0) {
btnPrev.setVisibility(View.INVISIBLE);
pagenum = pagenum + 1;
}
else {
recentCracks = web.getAllRecentCrackUps(pagenum);
if (recentCracks != null) {
adapter = new DynamicListAdapter(KidsCrackMeUp.this, recentCracks);
lstRecentPosts.setAdapter(adapter);
}
txtPageCount.setText(String.valueOf(pagenum));
txtTotalPages.setText(String.valueOf(totalpagecount));
}
if (pagenum == 1) {
//btnPrev.setEnabled(false);
btnPrev.setVisibility(View.INVISIBLE);
}
}
});
//Button Previous Ends Here-----------
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
pagenum = pagenum + 1;
btnPrev.setVisibility(View.VISIBLE);
TotalPages = TotalPages - 1;
//btnPrev.setEnabled(true);
if (TotalPages == 0) {
btnNext.setEnabled(false);
pagenum = pagenum - 1;
}
else
{
recentCracks = web.getAllRecentCrackUps(pagenum);
if (recentCracks != null)
{
adapter = new DynamicListAdapter(KidsCrackMeUp.this, recentCracks);
lstRecentPosts.setAdapter(adapter);
}
txtPageCount.setText(String.valueOf(pagenum));
txtTotalPages.setText(String.valueOf(totalpagecount));
}
if (TotalPages == 1) {
**strong text**// btnNext.setEnabled(false);
btnNext.setVisibility(View.INVISIBLE);
}
}
});
//Button Next Ends Here----
}
else
{
btnNext.setVisibility(View.GONE);
}
// rel.setVisibility(View.VISIBLE);
lstRecentPosts.setAdapter(adapter);
Please elaborate your question.I didnt get anything from it.
if you are trying to display two separate lists of same type then i would suggest you to go with SeparatedListAdapter

Categories

Resources