Java-BackGround color never applying - java

I'm trying to change the background color of buttons programatically in my Android application, but it does not work.
Whatever methods I am using work fine, (i.e text size, text, text color) but I cannot manage to change the background color of the buttons.
What am I doing wrong ?
XML description of the button :
<Button
android:id="#+id/jeton103"
android:layout_column="0"
android:layout_row="28"
android:layout_height="88dp"
android:layout_width="88dp"
android:backgroundTint="#2aa17b" />
Java code :
int i;
int j = 103;
Button changer;
private EditText changerlettres;
String choix;
public void BtnClick() {
changer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Thrown out letters
choix = changerlettres.getText().toString(); // EditText
for (int i = 0, n = choix.length(); i < n; i++) {
char letter = choix.charAt(i);
final Button jetoninvisible;
int ressourceId2 = getResources().getIdentifier("jeton"+j, "id", getPackageName());
jetoninvisible = (Button) findViewById(ressourceId2);
// jetoninvisible.getBackground().setAlpha(200); // Not working
// jetoninvisible.setBackgroundColor(Color.WHITE); Not working
// jetoninvisible.setTextColor(Color.parseColor("#eeceac")); // Not working
jetoninvisible.setTextSize(40); // Working fine
jetoninvisible.setText(String.valueOf(letter)); // Working fine
j = j+1;
}
}
});
}
Thanks a lot for your answers or suggestions

Related

Get Chip Text on click chip

I am new to android and trying to play with chips. I have chip group like this in xml
<com.google.android.material.chip.ChipGroup
android:padding="10dp"
android:id="#+id/tags"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:chipSpacing="10dp">
</com.google.android.material.chip.ChipGroup>
I am dynamically adding chip like this in it.
Chip chip = new Chip(getLayoutInflater().getContext());
for(String genre : tags_text) {
chip.setText(genre);
tags.addView(chip);
}
Adding chip is working fine. Now I want get chip text of clicked chip. I am trying to get it like this
chip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int chipsCount = tags.getChildCount();
String TagText ="";
int i = 0;
while (i < chipsCount) {
Chip chip = (Chip) tags.getChildAt(i);
if (chip.isChecked() ) {
TagText = chip.getText().toString();
}
i++;
};
Log.e("CHIPS", TagText+"-OK");
}
});
But I am getting empty text always. let me know if someone can help me for solve it.
Thanks!
You can use:
chip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = ((Chip) view).getText().toString();
//...
}
});

Building a variable upon buttons to trigger listeners

I am breaking my head dealing with variables types in my app.
I try in a loop to increase a var and pass it to a listener, according to the name of the buttons defined in my XML layout.
I would like to start from "jeton1" to "jeton2","jeton3"...., but cannot manage to do that in my code (errors arising), the vars do not point to the buttons stored in the XML and not showing up when calling the buttons listeners.
I made a test with a defined array but the stuff failed.
Test code below made upon only one button.
A help would be greatly appreciated.
Here is my code
The XML layout :
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="20"
android:columnCount="9">
<Button
android:id="#+id/jeton1"
android:layout_column="0"
android:layout_row="0"
android:text="#string/boutona"
android:layout_height="88dp"
android:layout_width="88dp"
android:textSize="40sp"
android:backgroundTint="#eeceac"
android:textStyle="bold" />
Main Java :
public class MainActivity extends AppCompatActivity {
int i;
String jeton = "";
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Main loop
for (i = 1; i < 2; i++) {
jeton = "jeton" + i; // Should throw "jeton1", "jeton2".....
final Button jetonnew;
jetonnew = (Button) findViewById(R.id.jeton); // Error 'cannot resolve symbol
// jetonnew = (Button)findViewById(R.id.jeton+i);
// Step 4 Listener
jetonnew.setOnTouchListener(
new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
jetonnew.getBackground().setAlpha(0); // Crash app
jetonnew.setTextColor(Color.parseColor("#2aa17b"));
break;
}
return true;
}
});
}
}
}
Many thanks for your replies and suggestions.
If you have a fixed number of buttons, you can store an array of integers
int[] ids = {R.id.button1, R.id.button2, ...};
However, if you want to dynamically add buttons, you should try creating them programmatically
Button newButton = new Button(this);
or you can create some custom layout and inflate it
inflate(this, R.layout.customLayout, null);
Keep in mind that R.id.someId returns and integer not a string so you cannot append to it. Also adding a string after id does not work for the same reason.
jetonnew = (Button)findViewById(R.id.jeton+i);
This portion of code does not work because R.id.jeton is a generated integer not a string.
You should consider using findViewByTag instead of findViewById. Your code will look like this:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="20"
android:columnCount="9">
<Button
android:tag="jeton1"
android:layout_column="0"
android:layout_row="0"
android:text="#string/boutona"
android:layout_height="88dp"
android:layout_width="88dp"
android:textSize="40sp"
android:backgroundTint="#eeceac"
android:textStyle="bold" />
So in your java file:
for (i = 1; i < 2; i++) {
jeton = "jeton" + i; // Should throw "jeton1", "jeton2".....
final Button jetonnew;
//findViewByTag here
jetonnew = (Button) findViewByTag(jeton)
Another way is to just iterate through GridLayout child, like this:
//suppose your gridLayout has id=#+id/gridparent
GridLayout gridParent = (GridLayout)findViewById(R.id.gridparent);
for(int index=0; index<gridParent.getChildCount(); ++index) {
Button nextButton = (Button)gridParent.getChildAt(index);
//attach listener here
}
You should create arrays of your grid button id's.
#IntegerRes int [] resourceButtonIds = new int[]{R.id.jeton1,R.id.jeton2};
Then modify the loop accordingly.
for (i = 0; i < resourceButtonIds.length; i++) {
final Button jetonnew;
jetonnew = (Button) findViewById(resourceButtonIds[i]);
// now set all your listeners
}
If you want to find the id of the button by using its name:
jetonnew = findViewById(getResources().getIdentifier("jeton" + i, "id", getPackageName()));

Multiple OnClick associated to WebViews inside loop

I want to link my Buttons to the associated WebViews. I have 2 lists, one of Button the other one of WebViews. What I'm trying to do is, showing or hiding the webView[x] associated to button[x]
nbObjects = 2;
Button[] buttons = null;
buttons = new Button[nbObjects];
buttons[0] = findViewById(R.id.button0);
buttons[1] = findViewById(R.id.button1);
WeView[] webViews = null;
webViews = new WebView[nbObjects];
webViews[0] = findViewById(R.id.webView0);
webViews[1] = findViewById(R.id.webView1);
for (int i = 0; i < nbObjects; i++) {
webViews[i].setVisibility(View.GONE);
final int j = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (webViews[j].getVisibility() == View.VISIBLE) {
webViews[j].setVisibility(View.GONE);
} else {
webViews[j].setVisibility(View.VISIBLE);
}
}
});
}
Result: when I click on Button0, everything works. WebView0 shows and hides. But not for WebView1 when I click on Button1.
Solution/Update
My WebViews are actually showing up. I added a background color to spot them when no URL was loaded. Now time to loadURL

How to get data from many EditTexts when Its added in layout programmatically in android

I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}

Get the Integer behind ImageView Array

I have this thing into my application.
That I want to do is this, when someone presses the die with the number 5 I want to add 5 points into his ArrayList. I was thinking for an Listener but how would I know which ImageView has been pressed?
Currently I am using this method to get the right placeholders in the board
public ImageView[] initiateDice() {
ImageView pDice1 = (ImageView) findViewById(R.id.die_one);
ImageView pDice2 = (ImageView) findViewById(R.id.die_two);
ImageView pDice3 = (ImageView) findViewById(R.id.die_three);
ImageView pDice4 = (ImageView) findViewById(R.id.die_four);
ImageView pDice5 = (ImageView) findViewById(R.id.die_five);
ImageView pDice6 = (ImageView) findViewById(R.id.die_six);
ImageView pDice7 = (ImageView) findViewById(R.id.die_seven);
ImageView pDice8 = (ImageView) findViewById(R.id.die_eight);
ImageView[] placeHolders = new ImageView[] {pDice1, pDice2, pDice3, pDice4, pDice5, pDice6, pDice7, pDice8};
return placeHolders;
}
and I am "printing" the dice on the screen using that method
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
}
}
where the first array is 8 random generated numbers for the dice and the second array is the PlaceHolders.
The diceImages is for the images of the dice, the six states of them.
private final int[] diceImages = new int[] {R.drawable.dice_one, R.drawable.dice_two, R.drawable.dice_three,
R.drawable.dice_four, R.drawable.dice_five, R.drawable.dice_pico };
Any thoughts or suggestions are welcome.
Other answers are providing some of the solution, but you're actually asking about how to get the number displayed in the image view, in which case, you can save it to the tag:
public void printDice(int[] array1, ImageView[] array2) {
for (int i = 0; i < array1.length; i++) {
array2[i].setImageResource(diceImages[array1[i] - 1]);
array2[i].setVisibility(View.VISIBLE);
array2[i].setTag(array1[i]);
}
}
And modifying Matt's answer:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
Integer dieValue = v.getTag();
// do something
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);
One way to do it is to set an OnClickListener like this:
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == pDice1) {
// do something
} else if (v == pDice2) {
...
}
}
};
pDice1.setOnClickListnener(listener);
pDice2.setOnClickListnener(listener);
pDice3.setOnClickListnener(listener);
pDice4.setOnClickListnener(listener);
pDice5.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice6.setOnClickListnener(listener);
pDice8.setOnClickListnener(listener);
You would set an OnClickListener() to all ImageViews. The OnClickListener() gets passed the View that has clicked. View has a getId() that returns an int with the id of the View. Then it is only a matter of adding either a switch or if(){...} else if(...)() to perform a specific action based on the id of the View that was clicked.

Categories