Browse an array of strings in a TextView - android

I wonder how I could navigate between the strings within an array, using the previous and next buttons, these strings will be displayed in a TextView. Thank you!
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f3);
setTitleFromActivityLabel (R.id.title_text);
TextView cumulos = (TextView) findViewById(R.id.cumulos);
TextView respostas = (TextView)findViewById(R.id.respostas);
Random randPhrase = new Random();
String[] cum = getResources().getStringArray(R.array.cumulos);
String[] resp = getResources().getStringArray(R.array.resp_cumulos);
String textout = "";
String textresp = "";
for (int i = 0; i < cum.length; i++) {
for (int j = 0; j < resp.length; j++) {
textresp = resp[j];
}
textout = cum[i];
}
cumulos.setText(textout);
respostas.setText(textresp);
}

Declare one int for index starting with 0 then in NextButton do
if(!index > resp.length-1 ) //not greater than array length
{
setText(resp[index++]);
}
else { nextButton.setEnabled(false); nextButton.setClicable(false); } //not clickable anymore
in PreviousButton do
if(!index < 0)
{
setText(resp[index--]);
}
else{
prevButton.setEnabled(false);
prevButton.setClicable(false);
}
Something like this? Mind this code is not tested, might throw exceptions.
It just to give you an idea.

You will need to create a next button and set an onClickListener for your button to navigate through the array. Lets say you also have a previous and next button. Try this:
Button btnNext = (Button) findViewById(R.id.yourNextbutton);
Button btnPrevious = (Button) findViewById(R.id.yourPreviousbutton);
int i = 0;
btnNext.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i<cum.length-1){
i+=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});
btnPrevious.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
if(i>0){
i-=1;
cumulos.setText(cum[i]);
respostas.setText(resp[i]);
}
}
});

Related

App crashing at the end of array

My app is crashing at the end of the array in bluestacks. I have no idea why.
When I click the next button at the end of the array, the app crashes. I also tested it on my phone, same result. The rest of the app functions as intended.
From what I know "i %= image_elements.length;" is supposed to be the function that loops the array.
I am pretty sure this is where the crash is coming from.
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
Full code below
public class Practice extends MainMenuActivity {
int i = 0;
final int[] image_elements = {
R.drawable.spr_elements_0,
R.drawable.spr_elements_1,
[...]
R.drawable.spr_elements_86,
R.drawable.spr_elements_87,
};
final int[] image_names = {
R.drawable.spr_name_0,
R.drawable.spr_name_1,
[...]
R.drawable.spr_name_86,
R.drawable.spr_name_87,
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
}
});
}
public void backButton(View view) {
Intent z = new Intent(this, MainMenuActivity.class);
startActivity(z);
}
}
You'll need to rearrange your code from this:
i++;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
i %= image_elements.length;
to this:
i++;
i %= image_elements.length;
element.setImageResource(image_elements[i]);
name.setImageResource(image_names[i]);
What happens otherwise is that the index is incremented beyond the boundaries of the array, and that is corrected afterwards with the modulus operator. You'll need to the the correction before you use the index.
i %= image_elements.length in this particular case, is essentially the same as
if( i == image_elements.length ) {
i = 0;
}
Arrays indices go from 0 to length-1.
You could get rid of the arrays entirely by looking up the resources by name, such as this:
final static int MAX_ELEMENTS = 88; // this includes 0..87
private int index = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practice);
final ImageView element = (ImageView) findViewById(R.id.element);
final ImageView name = (ImageView) findViewById(R.id.name);
final Resources res = this.getResources();
final String pkgName = this.getPackageName();
Button nextButton = (Button) findViewById(R.id.buttonNext);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final int imgId = res.getIdentifier( "spr_elements_" + index, "drawable", pkgName );
final int nameId = res.getIdentifier( "spr_name_" + index, "drawable", pkgName );
element.setImageResource( imgId );
name.setImageResource( nameId );
index = (index+1) % MAX_ELEMENTS;
}
});
}

how do I set up a next and previous button

Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}

Getting the array position of a array button during onClick

I have an array of button of size probably more than 20-30. My simple question is how to get the array index of the button that have been click? For example, i clicked btnDisplay[8] and then the apps will toast "8". As simple as that. but i don't know how to retrieve the index of the arrayed button.
switch (clickedButton.getId())
{
case R.id.Button01:
// do something
break;
case R.id.Button01:
// do something
break;
}
If i use this code, then i have to wrote like 20-30 cases. would there be a better solution?
How i generate button array
public class MainActivity extends Activity {
Button[] btnUpdate;
public void onCreate(Bundle savedInstanceState) {
//SOME CODE HERE
jsonParser = new JSONParser();
jObj = jsonParser.getJSONFromUrl(URL);
btnUpdate = new Button[jObj.length()];
for(int i=0;i<jObj.length();i++)
{
btnUpdate[i] = new Button(getApplicationContext());
btnUpdate[i].setText("Edit");
btnUpdate[i].setHeight(50);
}
Try this way
for (int i = 0; i < jObj.length(); i++) {
btnUpdate[i] = new Button(getApplicationContext());
btnUpdate[i].setText("Edit");
btnUpdate[i].setHeight(50);
btnUpdate[i].setTag(i); //ADD THIS LINE.
}
void onClick(View v) {
int index = (Integer) v.getTag();
Toast.makeText(getApplicationContext(), "BtnClicked"+index, Toast.LENGTH_SHORT).show();
}
Somehow try to use btnDisplay.indexof(); it works in C# I am not sure about Java
Try something like this
void onClick(View v)
{
int index = 0;
for (int i = 0; i < buttonArray.length; i++)
{
if (buttonArray[i].getId() == v.getId())
{
index = i;
Toast.makeText(getApplicationContext(), "BtnClicked"+index, Toast.LENGTH_SHORT).show();
break;
}
}
}

set and get android button text programatically [duplicate]

This question already has answers here:
Get text from pressed button
(8 answers)
Closed 8 years ago.
How can i get the text set on the button inside the on-click() class?
i need to get the button text for sq l select statement
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is");
}
});
c.moveToNext() ;
enter code here
You can type caste the view to button and use it to getText().
tableLayout.addView(tableRow);
int a = 0;
for (Integer j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(a++);
tableRow.addView(b);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer fff = v.getId();
Toast.makeText(getApplicationContext(), fff.toString(),
Toast.LENGTH_SHORT).show();
Button b = (Button)v;
String buttonText = b.getText().toString();
Log.d("TAG", "The text is " + buttonText);
}
});
c.moveToNext() ;
You are adding the Button to table row tableRow.addView(b);. I at first look at the code din't see it. Missed it.
So Make it final
final Button b = new Button(getApplicationContext());
// Use ActivtiyContext
final Button b = new Button(ActivityName.this);
// posted a link at the end read it.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
Inside onClick
public void onClick(View v) {
String value = b.getText().toString()
}
Also check
When to call activity context OR application context?
As per my way create String Array and :
String Title = new String[count];
And now implement like this:
for (int j = 0; j < count; j++)
{
Button b = new Button(getApplicationContext());
b.setText(c.getString(c.getColumnIndex("jour")));
b.setId(j);
Title[a] = c.getString(c.getColumnIndex("jour");
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v1) {
Toast.makeText(getApplicationContext(), "Button click on(): "+Title[v1.getId()].toString(), Toast.LENGTH_SHORT).show();
Log.d("TAG", "The index is: "+v1.getId());
}
});
tableRow.addView(b);
c.moveToNext() ;
}
Try this code:
public void onClick(View v) {
String value = (Button)v.getText().toString()
}
First you give onclick event for Button like (buttonClick).
final Button testButton = new Button(getApplicationContext());
void buttonClick(View v){
Log.v("text", testButton.getText().toString()); // get the text
testButton.setText("sometext"); //to change the text
}

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

Categories

Resources