Android change text color of button programmatically - android

I am creating button dynamically in linearlayout horizontalscrollview and on click i get selected button position.
I want to know how to change text color of selected button?
Here is my code.
String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT", "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
btn.setText(categories[i]);
btn.setBackgroundColor(Color.parseColor("#ffffff"));
btn.setOnClickListener(buttonClick);
ll.addView(btn);
int idx = ll.indexOfChild(btn);
btn.setTag(Integer.toString(idx));
// btn.setId(idx);
}
}
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
//(String)v.getTag();
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};

check the type and assign the text color
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
if(v instanceof Button){
((Button)v).setTextColor(Color.parseColor("#000000"));
}
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};

try this
Edited Answer
((Button)view).setTextColor(Color.parseColor("#000000"));

please check the following answer here and here .
as you can see you can do it programmatically and through xml by creating a style file for all of the states of the button .
Hope that helps

This works:
button.setTextColor(getColor(R.color.blue))

I just check all already posted solutions. No one works.
They also produce error like this
btnjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setTextColor(int)' on a null object reference
Real Solution :
Step-1: When you try to change setTextColor then always use try/catch, to prevent app from Crash.
Step-2: No matter you define your Button already, define(like R.id.btnId) again before setTextColor code line.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.btnId);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use try/catch for handle any kind of error
try {
Button btnForTextColorChange= (Button) findViewById(R.id.btnId);
// must define Button again before setTexColor code line
btnForTextColorChange.setTextColor(getResources().getColor(R.color.white));
} catch (Exception e){
Log.e(TAG, "Error:"+e);
}
}
});
}
[sorry for bad english]
Happy Coding :)

This worked for me:
btnItem.setTextColor(ContextCompat.getColor(context, R.color.black))

Related

Use a button to add other buttons, editText etc.

I need to be able to add buttons to a layout using an "add" button. The problem is that I need each button to have an OnClickListener()/onClick method. I was thinking every time the "add" button is pressed then i would add a new button to an array but im not sure add the listener and implement an onClick method for each button I create.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SmartChronometer chrono = (SmartChronometer) findViewById(R.id.chrono);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (chrono.isRunning())
chrono.pause();
else {
chrono.chronoStart();
}
}
});
}
I need to add chronomoter,button and listeners every time I click an "Add" button.
set all the clicklisteners as you wich!
call findViewById(R.id.btnSecond).setVisibility(View.GONE); on creat, then when clickin the first button
Button btnSecond;
...
public void onClick(View v) {
findViewById(R.id.btnSecond).setVisibility(View.VISIBLE);
if (btnSecond.getVisibility() == View.VISIBLE); {
findViewById(R.id.btnThird).setVisibility(View.VISIBLE);}
}
this way you can put all your information in the java file and all buttons in xml, but they will be hidden until click.
This is one way, other answer my come. Good Luck :)
implements OnClickListener
Button add = (Button) findViewById (R.id.addButton);
add.setOnClickListener (this);
List<Button> buttons = new ArrayList <Button>();
for (int i = 0; i < buttons.size (); i++){
buttons.get (i).setOnClickListener (this);
}
#Override
public void onClick (View v){
for (int i = 0; i < buttons.size (); i++){
if (v.getId () == buttons.get (i).getId ()){
// do stuff you want
}else if (v.getId() == R.id.addButton){
//add button
}
}
}
Hope this will work, didnt test it.

How to declare intent,class,buttons in one loop?

Why this doesn't work?
public class MainActivity extends Activity {
Button[] b = null;
Intent[] intent=null;
Class[] klasa;
Typeface font;
TextView glavninaslov;
ImageView plavi,ljubicasti;
AnimationDrawable plavian,ljubicastian;
String[] naslovi;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] naslovi = {"","First","Second","Third","Fourth","Fifth"};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
for(i=1;i<6;i++)
{
klasa[i]=Class.forName(naslovi[i]);//Problem is in:"Class not found exception"
intent[i] = new Intent(MainActivity.this,klasa[i]);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[i]);
gasenje();
}
});
}
Can anyone help me...?
Does anyone had similar problems?
Please help me...
The rest of code cannot affect on program... Please help me... I would appreciate it...
I have updated my code...it starts mainactivity but when i click on some button it crush app...
Button[] b = null;
Intent[] intent=null;
Typeface font;
TextView glavninaslov;
ImageView plavi,ljubicasti;
AnimationDrawable plavian,ljubicastian;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
intent = new Intent[b.length];
for(i=0;i<5;i++)
{
intent[i] = new Intent(MainActivity.this,naslovi[i]);
b[i].setTag(i);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[(Integer)v.getTag()]);
gasenje();
}
});
}
This code works...thanks guys
Update:
Rather than using reflection as you are to create these classes, as kcoppock suggested you should just do this:
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
And then in your loop:
intent[i] = new Intent(MainActivity.this, naslovi[i]);
Original Answer:
Assuming you have a classes called First, Second, etc, you need to include the package name:
String[] naslovi = {"",
"com.package.First",
"com.package.Second",
"com.package.Third",
"com.package.Fourth",
"com.package.Fifth"};
Replace com.package with the package for each class.
Also after you fix that, I foresee that you'll then get an IndexOutOfBoundsException - remove the blank "" element from naslovi, and change your for loop to for(i=0;i<5;i++)
The problem is that i will not be retained at the current value when the OnClickListener is executed. You can use the buttons' tag value to retain the proper value.
for (int i=0; i<b.length; i++) {
//existing logic
b[i].setTag(i);
b[i].setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(intent[(Integer)view.getTag()]);
}
});
}

get OnClick() from programmatically added buttons?

i have added some button in a layout:
LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
keys=db.getKeys(console);
my_button=new Button[keys.size()];
for (bt=0;bt<keys.size();bt++){
my_button[bt]=new Button(this);
my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
my_button[bt].setText(keys.get(bt));
my_button[bt].setId(bt);
row.addView(my_button[bt]);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[bt].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
}
}
});
}
I want to know which button is clicked and how to get text of the clicked button?And I think using bt here dose not seem to work!
This code is running. I hope it help you :)
final ArrayList<String> Keys = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
Keys.add("Keys is : " + String.valueOf(i));
}
LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);
final Button[] my_button = new Button[Keys.size()];
for (int bt = 0; bt < Keys.size(); bt ++){
final int Index = bt;
my_button[Index] = new Button(this);
my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
my_button[Index].setText(Keys.get(Index));
my_button[Index].setId(Index);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[Index].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
}
}
});
Row.addView(my_button[Index]);
}
ExampleProject id : Your project
You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.
Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as #qberticus described.
Consider This example :
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
This works fine :)

Listener(s) for array of buttons

For my own practice I am a creating an array of 3 buttons in the instance field and i would like all of them to have setOnClickListeners,which allow each button to change the BackGround Color of a text View.Can any person please guide me towards the right direction.Here is my code:
public class MainActivity extends Activity {
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
for(int i=0; i < b.length;i++){
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(butt[0].isPressed()){
tv.setBackgroundColor(Color.BLACK);
}
if(b[1].isPressed()){
tv.setBackgroundColor(Color.BLUE);
}
if(b[2].isPressed()){
tv.setBackgroundColor(Color.RED);
}
}
});
}
}
}
You aren't declaring an Array for your Buttons. I'm not sure what this would do or if it would even compile but I wouldn't think so
Button b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Change it to
Button[] b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),};
Also, this code has to go after setcontentView() or you will get a NPE since your Buttons exist in your layout and your layout doesn't exist until you inflate it by calling setContentView().
You can declare your Array before onCreate() but you can't initialize them until you inflate your layout
So you can do something like this
public class MainActivity extends Activity {
Button[] b = new Button[3]; //initialize as an array
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = {(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),}; //add buttons AFTER calling setContentView()
...
Edit Since #pragnani deleted his answer I will edit with a bit of it that is a good idea
You can simplify your logic by choosing which Button was clicked with a switch by doing something like below in your for loop
b[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { / v is the button that was clicked
switch (v.getId()) //so we get its id here
{
case (R.id.button1):
tv.setBackgroundColor(Color.BLACK);
break;
case (R.id.button2):
tv.setBackgroundColor(Color.BLUE);
break;
case (R.id.button3):
tv.setBackgroundColor(Color.RED);
break;
}

Array of android buttons

Can't work out a way to make an array of buttons in android.
This is the code I have tried but I'm getting a java.lang.NullPointerException.
private Button[] button = {(Button) findViewById(R.id.cGuess1),
(Button) findViewById(R.id.cGuess2),(Button)
findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};
Is this even possible?
EDIT:
Sorry everyone. Just realised my mistake!
I was trying to declare the array for my whole class and trying to get the views from the ids before onCreate so there was no setContentView(R.layout.game);
Sorry.
Since no one else posted actual code for a solution, here's a working snippet.
Button[] myButtons = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButtons = new Button[]
{
(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),
};
}
Just a guess as full code is not available here, have you called setContentView() before creating array.
Could you try
final Button[] button = {(Button) findViewById(R.id.cGuess1),
(Button) findViewById(R.id.cGuess2),(Button)
findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};
One of your buttons may be null. And putting a private keyword does not allow me to create the array. Also see that Firstly you are setting the cententView for your activity and then accessing these buttons.
public class main2 extends Activity{
final int[] button = {R.id.button1,R.id.button2,R.id.button3,R.id.button4,R.id.button5,
R.id.button6,R.id.button7,R.id.button8,R.id.button9,R.id.button10};
Button[] bt = new Button[button.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign);
for(int i=0;i<button.length;i++){
final Context context = this;
final int b = i;
bt[b]= (Button) findViewById(button[b]);
Typeface font = Typeface.createFromAsset(getAssets(), "Angkor.ttf");
bt[b].setTypeface(font);
bt[b].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context,r1.class);
startActivity(myIntent);
}
});
}
}
}

Categories

Resources