Android Declare buttons programmatically? - android

In my soundboard app I have 80 buttons that have a on click listener and a on long click listener.
My buttons are declared in xml as:
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content" >
<Button
android:id="#+id/sound0"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound0" >
</Button>
<Button
android:id="#+id/sound1"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound1" >
</Button>
<Button
android:id="#+id/sound2"
android:layout_width="1dip"
android:layout_height="fill_parent"
android:layout_weight=".31"
android:longClickable="true"
android:text="#string/sound2" >
</Button>
</TableRow>
And the listeners are set as:
Button SoundButton0 = (Button) findViewById(R.id.sound0);
SoundButton0.getBackground().setAlpha(150);
SoundButton0.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Play", name, 0);
playSound(R.raw.sound0);
}
});
SoundButton0.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
String name = getString(R.string.sound0);
tracker.trackEvent("Clicks", "Saved", name, 0);
ring(soundArray[0], name);
return false;
}
});
Is there a way I can do all of this programmatically in a for loop so that the only thing changed for each button is SoundButtonx where x is increased by one for each button.

Yes there is a clear solution:
Button[] buttons;
for(int i=0; i<buttons.length; i++) {
{
String buttonID = "sound" + (i+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i] = ((Button) findViewById(resID));
buttons[i].setOnClickListener(this);
}
Note: Declare XML layout with buttons having id like sound1, sound2, sound3, sound4....and so on.
A more clear-cut example is here for the same problem => Android – findViewById() in a loop

Yes there is. Inside your for loop, you first declare a Button, and pass its constructor a context. Then you set each button's layout params. Add each button to the parent view (use the addView method on the parent view). Finally, use the setContentView method of the activity and pass the parent as a param.

yes take a look at this
for(int x = 0;x<80;x++)
{
Button btn = new Button(this);
btn.setlayoutParams(new LayoutParams(LayoutParams.wrap_content,LayoutParams.wrap_conmtent);
btn.setId(100 + x);
btn.setOnClickListener(this);
btn.setOnlongClickListener(this);
this.addView(btn);
}
//this will create 80 buttons and setlisteners on them
//in your overrides of onclick and onLongClick identiffy them as
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
if(id == 100 + 1 )
{
//your code
}

Related

startActivity() inside setOnClickListener not doing anything

I have a button inside a view that checks some constraints, and then starts another activity, however the startActivity() call does not do anything, the new activity's onCreate() never gets called, and the code then continues past it. I have checked using logging and breakpoints, and the conditions are being met and startActivity() is being called. Both activities are defined in the application manifest.
From the source activity's onCreate():
int[] winning_player;
int next_player;
int[] scores;
[...]
final Button end_turn_button = (Button) findViewById(R.id.end_turn);
end_turn_button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (winning_player[0] == next_player) {
Intent intent = new Intent(getApplicationContext(), FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
});
FinalScreenActivity.java
public class FinalScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_screen);
Intent intent = getIntent();
final int[] scores = intent.getIntArrayExtra("SCORES");
// put the scoreboard in ascending order
Arrays.sort(scores);
// find the scoreboard in the view
TableLayout scoreboard = (TableLayout) findViewById(R.id.scoreboard);
// get the string resources to be formatted
Resources res = getResources();
String player_name_format = res.getString(R.string.player);
// Set the scoreboard in the view
Log.d("brains.PlayActivity", "onCreate: Creating scoreboard");
// for each player entry in the scoreboard
for (int i = 0; i < scores.length; i++) {
Log.d("brains.PlayActivity", "onCreate: adding scoreboard entry "+String.valueOf(i));
// create 2 TextViews
TextView player_name = new TextView(FinalScreenActivity.this);
TextView player_score = new TextView(FinalScreenActivity.this);
// Set the size of the TextViews
player_name.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
// set the first one to the player's name string resource
player_name.setText(String.format(player_name_format, i + 1));
// set the second one to the player's score resource, which takes the score twice (once for the number itself, and once to work out which plural is needed)
player_score.setText(res.getQuantityString(R.plurals.brains, scores[i], scores[i]));
// Create a TableRow to put the score into
TableRow scoreboard_entry = new TableRow(FinalScreenActivity.this);
// Set the size of the TableRow
scoreboard_entry.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
// Add the TextViews to the TableRow
scoreboard_entry.addView(player_name);
scoreboard_entry.addView(player_score);
// Add the TableRow to the TableLayout
scoreboard.addView(scoreboard_entry);
}
// Get the title text
TextView title_text = (TextView) findViewById(R.id.title_text);
title_text.setText(res.getQuantityString(R.plurals.win_brains, scores[scores.length - 1], scores.length - 1, scores[scores.length - 1]));
// set the play again button
Button play_again_button = (Button) findViewById(R.id.play_again_button);
play_again_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), SelectPlayersActivity.class);
startActivity(intent);
}
});
}
}
and activity_final_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="uk.co.bluesapphiremedia.android.zombiedice.FinalScreenActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/title_text"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="#+id/scoreboard"
android:layout_below="#+id/title_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_again"
android:id="#+id/play_again_button"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
end_turn_button.setOnClickListener(this);
//override onClick() method in activity implement interface View.OnClickListner
public void onClick(View v) {
if(v.getId() == R.id.end_turn){
if (winning_player[0] == next_player) {
Intent intent = new Intent(this,FinalScreenActivity.class);
intent.putExtra("SCORES", scores);
startActivity(intent);
}
}
}

One activitiy with different backgrounds in android

I am trying to create an android app. I have two buttons next and back in my android app. I want when i click on next button its open same activity with different background. Next time i again click next new background image. And on press on back button its show previous image. And if no previous image its shows menu on press. Similarly if background with last image its hide next button. I have no idea how to do this.
I have tried this:
#Override
public void onCreate(Bundle savedInstanceState)
{
onCreate(savedInstanceState);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.back)
{
startActivty(new Intent(this,));
}
else if(v.getId()==R.id.next)
{
startActivity(newIntent(this,));
}
}
Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/back">
<Button
android:id="#+id/back"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="25dp"
android:background="#drawable/ques"
android:text="Back" />
<Button
android:id="#+id/next"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/back2"
android:layout_alignBottom="#+id/back2"
android:layout_alignParentRight="true"
android:background="#drawable/ques"
android:text="Next" />
</RelativeLayout>
In layout as you can see i am using image back for background. I want when i click next new background image then next and so on.
But i dont know how to start same activity with differene backgroud.
Don't start new Activity just change the background:
Keep an array of background resources in your activity like:
int[] backgroundResId;
and one int variable to store current background index:
int currentIndex=0;
now inside your onCreate initialize this array with resource id's of all the backgrounds drawables:
backgroundResId=new int[]{R.drawable.a,R.drawable.b,R.drawable.c};
changeBackground()
create function changeBackground in activity:
private void changeBackground(){
findViewById(R.id.root_layout).setBackgroundResource(backgroundResId[currentIndex]);
}
Now onClick of next button increase currentIndex:
currentIndex++;
if(current<=backgroundResId.length){
changeBackground();
}else{
// setVisibility of next button to invisible
}
onBackButton Click
currentIndex--;
if(current>=0){
changeBackground();
//// setVisibility of next button to visible
}else{
//show menu
}
Make an images array and post your data to the next activity:
Intent intent = getIntent();
intent.putExtra("background", imageIdInTheImageArray);
startActivity(intent);
//finish();
and in your onCreate function :
Bundle b = getIntent().getExtras();
if (b != null) {
int background = b.getInt("background");
//set your background
}
You can add an ImageView in your xml file.
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
you can change background using this
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setBackgroundResource(resId);
Try this..
Global:
int[] backgrounds = new int[]{ images in drawable as int array };
int count = 0;
Button back,next;
RelativeLayout img_backn_lay;
JAVA:
setContentView(R.layout.activity_main);
back = (Button) findViewById(R.id.back);
next = (Button) findViewById(R.id.next);
back.setOnClickListener(this);
next.setOnClickListener(this);
img_backn_lay = (RelativeLayout) findViewById(R.id.main_lay);
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
ClickListener:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.next)
{
if(backgrounds.length != count){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count += 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
else if(v.getId()==R.id.back)
{
if(count != 0){
img_backn_lay.setBackgroundResource(backgrounds[count]);
count -= 1;
}else{
Toast.makeText(MainActivity.this, "No images", Toast.LENGTH_LONG).show();
}
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_lay"
android:layout_width="match_parent"
android:layout_height="match_parent" >

onLongClick listener for group of buttons in Android

In my Android application, I want to create a fragment that works like a keypad. I have one function which handle onClick for all 9 keys. I want to know is there anyway to write just one function to handle onLongClick for all these 9 keys too.
here is layout xml :
<Button
android:id="#id/testButton"
android:layout_width="70dp"
android:layout_height="55dp"
android:layout_margin="2dp"
android:background="#drawable/keypad_round_button"
android:text="1"
android:textColor="#color/black_1"
android:onClick="keypadSetNote"
android:longClickable="true"/>
<Button
android:id="#id/testButton"
android:layout_width="70dp"
android:layout_height="55dp"
android:layout_margin="2dp"
android:background="#drawable/keypad_round_button"
android:text="2"
android:longClickable="true"
android:textColor="#color/black_1"
android:onClick="keypadSetNote"
/>
Here is OnlongClick listener :
Button button = (Button) findViewById(R.id.testButton);
button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Button clickedButton = (Button) v;
String buttonText = clickedButton.getText().toString();
Log.v(TAG, "button long pressed --> " + buttonText);
return true;
}
});
I gave all keys same ID to handle all onLongClick actions in one function, but it just work for the first key. Is there anyway to define something like group button in Android ??? Or I have to write OnLongClick listener for all of them separately ???
Just create a named function instead of an anonymous one:
View.OnLongClickListener listener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Button clickedButton = (Button) v;
String buttonText = clickedButton.getText().toString();
Log.v(TAG, "button long pressed --> " + buttonText);
return true;
}
};
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
button3.setOnLongClickListener(listener);
And, altough you don't asked it, we must warn you: As #AndyRes says, your buttons must have differents ids. Having the same ID doesn't mean that getting the button by id will return all buttons, only will return the first button with that ID, that's because it only works with the first button.
Buttons should have different ids:
<Button
android:id="#id/testButton1"
//... />
<Button
android:id="#id/testButton2"
//... />
<Button
android:id="#id/testButton3"
//... />
Now, to set the listener for all, a solution would be to get the id of all buttons in an array, and then use a "for" loop to set the listener for each.
Like this:
// Store the id of buttons in an array
int[] ids={R.id.testButton1, R.id.testButton2,R.id.testButton3};
// loop through the array, find the button with respective id and set the listener
for(int i=0; i<ids.length; i++){
Button button = (Button) findViewById(ids[i]);
button.setOnLongClickListener(longClickListener);
}
View.OnLongClickListener longClickListener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// .....
return true;
}
};
if your buttons are in the LinearLayout, in the RelativeLayour or in the other. And you have very many buttons.
View.OnLongClickListener listener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Log.d("ID", ""+v.getId());
switch (v.getId())
{
case R.id.button1:
//do something for button1
break;
case R.id.button2:
//do something for button2
break;
...
}
return true;
}
};
LinearLayout layout=(LinearLayout)findViewById(R.id.IdOfLinearLayout);
for(int i=0;i<layout.getChildCount();i++){
layout.getChildAt(i).setOnLongClickListener(listener);
}
xml file for example...
<LinearLayout
android:id=#+id/IdOfLinearLayout"....>
<Button
android:id="#+id/button1"
android:layout_width=...
android:layout_height=...
.../>
<Button
android:id="#+id/button2"
... />
....
<Button
android:id="#+id/buttonN"
.../>
</LinearLayout>

How to scroll a HorizontalScrollView on button click in android?

I have horizontal scrollview in my android app with Next and Previous buttons.I want to show the these buttons only when the scollview needs scrolling.ie,width of scrollview content exceeds display width.Also want to hide previous and Next buttons when reaching first and last items respectively.How to to next/previous items when click on these buttons?
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
<Button
android:id="#+id/btnPrevoius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Previous"
android:visibility="gone" />
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_toLeftOf="#+id/btnNext"
android:layout_toRightOf="#+id/btnPrevoius"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Next"
android:visibility="gone" />
</RelativeLayout>
activity
public class SampleActivity extends Activity {
private static LinearLayout linearLayout;
private static HorizontalScrollView horizontalScrollView;
private static Button btnPrevious;
private static Button btnNext;
private static int displayWidth = 0;
private static int arrowWidth = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
btnPrevious = (Button) findViewById(R.id.btnPrevoius);
btnNext = (Button) findViewById(R.id.btnNext);
for (int i = 0; i < 15; i++) {
Button button = new Button(this);
button.setTag(i);
button.setText("---");
linearLayout.addView(button);
}
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
ViewTreeObserver obs = linearLayout.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
Display display = getWindowManager().getDefaultDisplay();
displayWidth = display.getWidth();
if (linearLayout.getMeasuredWidth() > (displayWidth - 40)) {
btnPrevious.setVisibility(View.VISIBLE);
btnNext.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(listnerLeftArrowButton);
horizontalScrollView.setOnTouchListener(listenerScrollViewTouch);
}
private OnTouchListener listenerScrollViewTouch = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
showHideViews();
return false;
}
};
private OnClickListener listnerLeftArrowButton = new OnClickListener() {
#Override
public void onClick(View v) {
horizontalScrollView.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, new KeyEvent(0, 0));
}
};
public static void showHideViews() {
int maxScrollX = horizontalScrollView.getChildAt(0).getMeasuredWidth()- displayWidth;
Log.e("TestProjectActivity", "scroll X = " +horizontalScrollView.getScrollX() );
Log.i("TestProjectActivity", "scroll Width = " +horizontalScrollView.getMeasuredWidth() );
Log.d("TestProjectActivity", "Max scroll X = " + maxScrollX);
if (horizontalScrollView.getScrollX() == 0) {
hideLeftArrow();
} else {
showLeftArrow();
}
if (horizontalScrollView.getScrollX() == maxScrollX) {
showRightArrow();
} else {
//hideRightArrow();
}
}
private static void hideLeftArrow() {
btnPrevious.setVisibility(View.GONE);
}
private static void showLeftArrow() {
btnPrevious.setVisibility(View.VISIBLE);
}
private static void hideRightArrow() {
btnNext.setVisibility(View.GONE);
}
private static void showRightArrow() {
btnNext.setVisibility(View.VISIBLE);
}
}
The 'maxScrollX' value is not correct for me.How to find maximum scrollvalue for this?
Thanks in Advance
This might come a bit late, but for anyone out there that will face this problem I suggest alternative solution(s).
First, use different component than HorizontalScrollView. Here are the options:
OPTION 1: Horizontal ListView - add this class to your project (create a separate package, something like com.yourproject.widgets). Also you'll need to create custom Adapter, see how that's done in this example. I suggest you create separate adapter class (exp. HorizontalListViewAdapter) and put it in already created com.yourproject.widgets package.
add this widget to your layout in the xml (put it between buttons that need to mimic the scrolling behavior) you'll need to add something like:
<com.yourproject.widgets.HorizontalListView
android:id="#+id/hList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
reference this (along with the buttons) in the Activity/Fragment that utilizes the widget
HorizontalListView mHList = (HorizontalListView) findViewById (R.id.hList);
Button bPrevoius = (Button) findViewById (R.id.btnPrevoius);
Button bNext = (Button) findViewById (R.id.btnNext);
add onClickListeners to the Buttons. Use the scrollTo() function predefined in the HorizontalListView widget. As you can see in the code, it takes int dp value to scroll. Add positive values if you want to scroll in right (next), and use negative values if you want to scroll in left (previous):
bPrevoius.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//value 500 is arbitrarily given. if you want to achieve
//element-by-element scroll you should get the width of the
//previous element dynamically or if the elements of the
//list have uniform width just put that value instead
mHList.scrollTo(-500);
//if it's the first/last element you can bPrevoius.setEnabled(false)
}
});
bNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mHList.scrollTo(500);
}
});
OPTION 2: More up to date solution to this issue can be the new widget RecyclerView introduced in Android L (addition of android:scrollbars="vertical" seems that would do the trick; other than that should have conventional ListView behavior). For more info check the official documentation.
devu
Plz have a look at the following links
1) http://android-er.blogspot.in/2012/07/implement-gallery-like.html
2) http://androiddreamers.blogspot.in/2012/09/horizontal-scroll-view-example.html
3)http://code.google.com/p/mobyfactory-uiwidgets-android/
Let me know if u r facing any issues
Thanks
In titanium appcelerator, you can do this using scrollableView
var scrollableView = Ti.UI.createScrollableView({
showPagingControl:true,
scrollingEnabled: true,
top: 360
});
Then, you can run a loop of all images or any content that you have, and add them to this view.
for(loop) {
eval("var view"+i+"=Ti.UI.createView();");
profile_image = Ti.UI.createImageView({
image: result[0]['profile_image'],
left:15,
width:82,
height:104,
top: 0
});
eval("view"+i+".add(profile_image);");
eval("scrollableView.addView(view"+i+");");
}
mywin.add(scrollableView);

How to get value of a pressed button

Hi all I am new to android development, infact its my first application. I want to know
<button
android:text="1" />
in above tag, text is the value of the button? if yes then how i can get this value or store it in a variable. if not, then how to define a value behind any button in android?
yes its a value of Button , use following code to fetch Text of Button.
Button b = (Button)findViewById(R.id.button1);
String buttonText = b.getText().toString();
function call
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
function();
}
});
You first need to give the button an id, like so:
<Button
android:id="#+id/buttonId"
android:text="1"
/>
And then in your code do something like:
Button b = (Button)findViewById(R.id.buttonId);
b.getText(); // returns the value of your text.
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ButtonText" />
...
#Override
public void onCreate(Bundle savedInstanceState) {
Button btn = (Button) findViewById(R.id.button1);
String text = btn.getText().toString();
}

Categories

Resources