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

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

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.

Android change text color of button programmatically

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

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 :)

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

Android Button setAlpha

There are a set of buttons, I want to get the result:
When I click one of them, first I divide them into two parts: the clicked one and the others. I'm trying to set different color or alpha value to different them.
Now I use setAlpha, but when I change the value from 0 to 255, it works, but when I change the value from 255 to 0 , it doesnot work. I don't know why.
Maybe after I invoke the methodButton.setAlpha(), I need invoke another method?
my code:
public class MainActivity extends Activity {
// button alpha value: minimize value
public static int BUTTON_ALPHA_MIN = 0;
// button alpha value: maximize value
public static int BUTTON_ALPHA_MAX = 255;
private LinearLayout centerRegion;
private LinearLayout bottomRegion;
private Button btnCheckIn;
private Button btnReview;
private Button btnMyCircles;
private Button btnSettings;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get all the widgets
getAllWidgets();
// set buttons click response function
btnCheckIn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.RED);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
}
});
btnReview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.BLUE);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MIN);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
}
});
btnMyCircles.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.YELLOW);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnSettings.getBackground().setAlpha(BUTTON_ALPHA_MAX);
v.getBackground().setAlpha(BUTTON_ALPHA_MIN);
}
});
btnSettings.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
centerRegion.setBackgroundColor(android.graphics.Color.MAGENTA);
btnCheckIn.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnReview.getBackground().setAlpha(BUTTON_ALPHA_MAX);
btnMyCircles.getBackground().setAlpha(BUTTON_ALPHA_MAX);
v.getBackground().setAlpha(BUTTON_ALPHA_MIN);
}
});
}
/**
* get all the widgets
*/
public void getAllWidgets() {
this.centerRegion = (LinearLayout) this.findViewById(R.id.center_region);
this.bottomRegion = (LinearLayout) this.findViewById(R.id.bottom_region);
this.btnCheckIn = (Button) this.findViewById(R.id.button_check_in);
this.btnReview = (Button) this.findViewById(R.id.button_review);
this.btnMyCircles = (Button) this.findViewById(R.id.button_my_circles);
this.btnSettings = (Button) this.findViewById(R.id.button_setting);
}
}
Using AlphaAnimation should work; verified on my device.
public class Test extends Activity implements OnClickListener {
private AlphaAnimation alphaDown;
private AlphaAnimation alphaUp;
private Button b1;
private Button b2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout) findViewById(R.id.linear_layout);
b1 = new Button(this);
b1.setText("Button 1");
b1.setOnClickListener(this);
ll.addView(b1);
b2 = new Button(this);
b2.setText("Button 2");
b2.setOnClickListener(this);
ll.addView(b2);
alphaDown = new AlphaAnimation(1.0f, 0.3f);
alphaUp = new AlphaAnimation(0.3f, 1.0f);
alphaDown.setDuration(1000);
alphaUp.setDuration(1000);
alphaDown.setFillAfter(true);
alphaUp.setFillAfter(true);
}
public void onClick(View v) {
if (v == b1) {
b1.startAnimation(alphaUp);
b2.startAnimation(alphaDown);
} else {
b1.startAnimation(alphaDown);
b2.startAnimation(alphaUp);
}
}
}
The key is calling setFillAfter(true) so that the alpha change persists.
Thanks for the question and the answer. This really helped me out.
For my solution, I needed to set the alpha of a button without seeing any animation effect, but the button.setAlpha(x) was failing sporadically. Using animations instead did the trick, but I had to set the duration to zero to get the automatic effect.
alphaDown = new AlphaAnimation(1.0f, 0.3f);
alphaUp = new AlphaAnimation(0.3f, 1.0f);
alphaDown.setDuration(0);
alphaUp.setDuration(0);
alphaDown.setFillAfter(true);
alphaUp.setFillAfter(true);
I use this for player controls in a media application, so I had something like this:
boolean bInitPrevEnabled = m_btPrev.isEnabled();
boolean bInitNextEnabled = m_btNext.isEnabled();
boolean bInitPlayEnabled = m_btPlay.isEnabled();
m_btPrev.setEnabled(true);
m_btNext.setEnabled(true);
m_btPlay.setEnabled(true);
// Process enabling of the specific buttons depending on the state
if (bInitPrevEnabled != m_btPrev.isEnabled())
m_btPrev.startAnimation((m_btPrev.isEnabled()) ? alphaUp : alphaDown);
if (bInitNextEnabled != m_btNext.isEnabled())
m_btNext.startAnimation((m_btNext.isEnabled()) ? alphaUp : alphaDown);
if (bInitPlayEnabled != m_btPlay.isEnabled())
m_btPlay.startAnimation((m_btPlay.isEnabled()) ? alphaUp : alphaDown);
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.main_btn);
Drawable d = getResources().getDrawable(R.drawable.imagen);
d.setAlpha(60);
btn.setBackgroundDrawable(d);
}
This works for me :)
public void setAlpha (int alpha) - deprecated
public void setAlpha (float alpha) (0f < alpha < 1f)
Added in API level 11

Categories

Resources