Change image to a button created programmatically - android

I have created a interface with buttons, but i don't know how many buttons I need to create, so I have created them in java, with this code:
public void criaButton (String nome){
TableLayout tl=(TableLayout)findViewById(R.id.tabBTALERT);
TableRow tr1 = new TableRow(this);
tr1.setPadding(17, 15, 15, 5);
final Button bt = new Button(this);
bt.setText(nome);
bt.setTextColor(Color.BLACK);
bt.setBackgroundResource(R.drawable.botao);
bt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.envelope, 0, 0, 0);
bt.setPadding(10, 20, 20, 20);
bt.setId(id);
tr1.addView(bt);
tl.addView(tr1);
bt.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
idButton = bt.getId();
nomeButton = (String) bt.getText();
inicia ();
Toast.makeText(Alerta.this, "Nome e ID : " + nomeButton + " " + idButton, Toast.LENGTH_SHORT).show();
}
});
}
with this method I can save the id and the name of every button I create. The problem is, these buttons have an image, and when I start another activity I have to change the image, if the message was read, not read, approved or rejected.
The question is, how can I give the id of the button to change the image and start again the activity with the changed image?? Is this possible?

Save the button ids in an array and then find the buttons by their ids and change their image to the desired one.

Related

How to save the updated value of an array back to the firestore database?

for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())) {
String value1 = snapshot.getString("QuestionName");
q_tv1.setText("Question: "+value1);
ArrayList<String> description = (ArrayList<String>) snapshot.get("Description");
Log.d(Tag,"output for des: "+description);
List<String> noOfOptions = (List<String>) snapshot.get("Options");
Log.d(Tag,"output for option: "+noOfOptions);
ArrayList<String> finalCount=(ArrayList<String>) snapshot.get("CountValue");
int size=noOfOptions.size();
Log.d(Tag,"size: "+finalCount);
for(i=0;i<=size-1;i++)
{
String op=noOfOptions.get(i);
String n=finalCount.get(i);
CardView cardview=new CardView(PublicVote.this);
LayoutParams layoutparams = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
LayoutParams layoutparams2 = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT
);
cardview.setLayoutParams(layoutparams);
cardview.setRadius(25);
layoutparams.setMargins(10,10,10,10);
layoutparams2.setMargins(10,100,100,100);
cardview.setPadding(25, 25, 25, 25);
cardview.setCardBackgroundColor(Color.TRANSPARENT);
cardview.setBackgroundTintList(ColorStateList.valueOf(Color.YELLOW));
cardview.setMaxCardElevation(30);
cardview.setMaxCardElevation(6);
TextView textview = new TextView(PublicVote.this);
textview.setLayoutParams(layoutparams);
textview.append("o " +noOfOptions.get(i));
textview.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview.setTextColor(Color.BLACK);
textview.setPadding(25,25,25,25);
textview.setGravity(Gravity.LEFT);
textview.setLayoutParams(layoutparams);
TextView textview1 = new TextView(PublicVote.this);
textview1.setLayoutParams(layoutparams);
textview1.append("Description: "+description.get(i));
textview1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
textview1.setTextColor(Color.BLACK);
textview1.setPadding(25,25,25,25);
textview1.setGravity(Gravity.LEFT);
textview1.setLayoutParams(layoutparams2);
cardview.addView(textview);
cardview.addView(textview1);
l1.addView(cardview);
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
}
});
}
}
This is my code above here my n1 is the countValue which is updated everytime the user clicks the cardview it keeps on incrementing. Now I want to save this incremented value i.e. the countValue (n1 here)back to the database which is given below.
Now here the options 121 and 122 have count value 10 and 5 respectively which gets incremented by 1 when any one option is clicked, lets say 121 is clicked so new value is 11 and 5(remains the same). This 11 and 5 needs to be updated back to the database, need help with this!
Hum, I suggest to set the settings in the XML layout instead of the setting in the class, it's more easy to visualize. If I understood should be like this, unless is another variable.
If the variable n1 is counting the numbers
Log.d(Tag,"n1->>: "+ n1);
Try todo this:
Log.d(Tag,"n1->>: "+ (n1 + 1));
or setting the number outside the operation
n1 = n1 + 1;
This way every time they click on is going to set the number +1, try to do what i said about the settings in the xml.
you can use the two atomic operations in Cloud Firestore:
Transactions or Batch Writes on your snapshot and the document.
Update data with transactions when button click event is called.
Use Batch Writes at some point of interval.
Check this link for reference.
You can add your write back to firestore action inside onClick method as below.
cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(PublicVote.this, n, Toast.LENGTH_SHORT).show();
n1 = Integer.parseInt(String.valueOf(n));
n1 = n1 + 1;
Log.d(Tag,"i->>: "+n1);
//update database
//add your update code here.
}
});
You can find more on [Firebase] Cloud Firestore — Add, Set, Update, Delete, Get data

How to find which dynamic button is clicked in android

i have created dynamic button in activity on button click. When i created more than on button in activity,onclick works for the most recent button as i assigned id to every button. how can i identify which dynamic button is pressed other than most recent button.
Here is the snippet of my code
public void dynamicButton()
{
// int x=0;
preferences = PreferenceManager.getDefaultSharedPreferences(TimeStudy.this);
value = preferences.getInt("value", 0);
//myButton = new Button(this);
// if (value > x)
if ( i <= value) {
myButton= new Button(this);
myButton.setId(value);
BtnId.add(value);
myButton.setTag(value);
LinearLayout ll = (LinearLayout) findViewById(R.id.dynamiclayout);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setPadding(10, 300, 10, 10);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
myButton.setLayoutParams(lp);
btnid= myButton.getId();
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (btnid) {
case 1:case 2:case 3:case
Intent intent = new Intent(TimeStudy.this, CollectSample.class);
startActivity(intent);
break;
}
}
});
ll.addView(myButton, lp);
i++;
}
switch (btnid) {
case 1:case 2:case 3:
SharedPreferences average = getSharedPreferences("avg", 0);
String avgbtn = average.getString("btnavg", "");
settings = getSharedPreferences("dynamicbtname", 0);
btnname = settings.getString("btnname", "");
ar.add(btnname);
String styledText = "<font color='#008000'>" + btnname + "</font>" + "&nbsp" + "&nbsp" + "&nbsp"
+ "<small>"
+ avgbtn + "</font>"
+ "<small>";
myButton.setText(Html.fromHtml(styledText));
myButton.setGravity(Gravity.CENTER | Gravity.LEFT);
break;
}
i want result like this even if after creation of all three button and 1 button is clicked no shows on first button.
enter image description here
i get this if i pressed 1 button after creation of 2 or third button data returns to most recent button.
enter image description here
any help appriciated thanks in advance.
THere's two ways.
1)Check by comparing it to the view variable passed in
2)Use an OnClickListener implementation that knows which one it is (by using different classes, or using one class with a parameter in it).

Creating new Textviews in another activity based onClick android

I would like to create a new textview to hold the information sent each time the button is clicked. I have the data I want passing to another screen in a textview but each time i try to put new data it overrides this data because it uses the same textView (textview4). I would like to know if there is a way of creating a new text view to hold my data each time the button is clicked. I hope I was clear enough, thanks.
This code is from a class called CreateWorkout.Java
public void createNewWorkout (View view){
TextView Exercise1TextView = (TextView) findViewById(R.id.Exercise1TextView);
EditText weightEntered = (EditText)findViewById(R.id.WeightLiftedEditText);
EditText reps = (EditText)findViewById(R.id.RepsEditText1);
EditText sets = (EditText)findViewById(R.id.setsEditText1);
Intent getWorkoutIntent = new Intent(this, SelectWorkout.class);
getWorkoutIntent.putExtra("Workout", Exercise1TextView.getText().toString()
+ " " + weightEntered.getText().toString() + "kg"
+ " " + reps.getText().toString() + " reps"
+ " " + sets.getText().toString() + " sets");
startActivity(getWorkoutIntent);
}
This is where the intent is called. This is from SelectWorkout.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_workout);
TextView textView4 = (TextView) findViewById(R.id.textView4);
textView4.setText(getIntent().getExtras().getString("Workout"));
}
i want to take the data entered here to the next screen. So the exercise name(Leg Press), weight(50), set(3), reps(10)
creating a new text view to hold my data each time
Not an exact answer, but this should guide you in the right direction. You could do something like the following:
Get your bundle
Iterate bundle
Create Textviews during iteration and add them to "your_main_layout" which is the id of the main layout inside select_workout
The bundle is the extra data you're sending over from the Intent. The Iterate is going through each item you sent over to this new intent, the create part refers to creating a TextView for each item you sent over. I've supplied links to what I found below.
Listing all extras of an Intent
//Get a bundle:
for (String key : bundle.keySet()) {
// This is each value (text) you sent over from the last intent
Object value = bundle.get(key);
//output data to log, so you can see what prints out
Log.d(TAG, String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
//adding a textview to a layout called your_main_layout (which can be a linear layout or something)
//with value.toString() as the text
your_main_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
value.toString(), 20, 10, 20));
}
How can I add a TextView to a LinearLayout dynamically in Android?
//method to create view:
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}

clickable span in a ListView

I'm trying to implement a comment like list where you can mention other users in the comments, and then be able to click on that to go to their profile. For example, when posting a comment on reddit you can mention another user with /u/username.
The one problem i'm running into is how to make it so I can click on the text to load that user's profile.
For the comment list I essentially have a custom list of textviews. From googling around I saw that it is possible to be able to click on some text in a textview using a clickable span. However, I haven't been able to get this to work in a list of textviews. Can someone help?
This is the relevant sections of my code:
Clickable span I declared as a member variable:
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View widget) {
Intent intent = new Intent(context, ProfileActivity.class);
// ParseUser.getQuery().whereEqualTo(Constants.kQollegeUserPreferredUsernameKey, sta)
intent.putExtra("User", ParseUser.getCurrentUser().getObjectId());
context.startActivity(intent);
}
};
Inside getView:
TextView answer_text_view = answerView.getAnswerTextView();
String text = answer.getAnswerText();
if(text.contains("#")) {
text += " ";
final SpannableStringBuilder sb = new SpannableStringBuilder(text);
List<Integer> start = new ArrayList<>();
int index = text.indexOf("#");
while (index >= 0) {
start.add(index);
index = text.indexOf("#", index + 1);
}
for(int i = 0; i<start.size(); i++){
sb.setSpan(fcs, start.get(i), text.indexOf(" ", start.get(i)), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
sb.setSpan(clickableSpan, start.get(i), text.indexOf(" ", start.get(i)), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
answer_text_view.setText(sb);
}
I have applied following to the textview where clickable span is present to make it work
textView.setMovementMethod(LinkMovementMethod.getInstance());

How to enable the record for delete after retrieve in sqlite?

I fetch record from database using following code.
for (LocWiseProfileBeans cn : LocWiseProfile) {
// get a reference for the TableLayout
TableLayout table = (TableLayout) findViewById(R.id.locprofile_table);
// create a new TableRow
TableRow row = new TableRow(this);
// count the counter up by one
counter++;
String log = "Loc Name: "+cn.getLocname()+" ,Lattitude: " + cn.getLattitude()+ " ,Longitude: " + cn.getLongitude()+ " , Selected Profile :"+cn.getSelectedprofile();
TextView t = new TextView(this);
// set the text to "text xx"
t.setText(cn.getLocname());
TextView t2 = new TextView(this);
t2.setText(cn.getSelectedprofile());
row.addView(t);
row.addView(t2);
table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
But i need to enable this record for deletion on user request.
Means if user click on second record then this record will be delete.
I try to find the answer but not find any appropriate answer.......
Please provide me reference code or article.
Thank you in Advance!
You can do this by setting onClickListener to your row.
To determine which row is clicked, you can set a unique tag to that row.
row.setTag(counter); // use counter or index for tag, so you can get the data from LocWiseProfile later
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int tag = (Integer)view.getTag();
LocWiseProfileBeans cn = LocWiseProfile.get(tag);
// Perform delete action here
// ...
}
});
If you want to simply display the result from db as a list, I suggest you using ListActivity or ListView, with using adapter you can show and manage your data in more simple way.
//decleration
EventDataSQLHelper eventsData; //Class where table is created
SQLiteDatabase dbx,rdbx;
//onCreate
eventsData = new EventDataSQLHelper(this);
rdbx= eventsData.getReadableDatabase();
dbx=eventsData.getWritableDatabase();
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//specify the id of the record to be deleted
dbx.delete("tablename", "id=" ?, null);
}
});

Categories

Resources