Android Butterknife add Textview onClick - android

I have an activity where the user enters some ingredient info and an add button. How would I add a textview using butterknife? I am currently getting no errors and nothing onscreen so I must be trying to implement this wrong.

I figured it out. this may not be the right way to do it but this is how I accomplished it.
I first add the binds
#BindView(R.id.btnAddIngredient)
Button btnAdd;
#BindView(R.id.addNextBtn2)
Button btnNext;
#BindView(R.id.ingListLayout)
LinearLayout linearLayout;
Then I added this code
#OnClick({
R.id.btnAddIngredient,
R.id.addNextBtn2
})
public void onClick(Button button) {
switch (button.getId()) {
case R.id.btnAddIngredient:
qty = edtxt1.getText().toString();
measurement = edtxt2.getText().toString();
Ingredient = edtxt3.getText().toString();
inputString = qty+" "+measurement+" of "+Ingredient;
TextView ing = new TextView(this);
ing.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ing.setText(inputString);
linearLayout.addView(ing);
edtxt1.setText(null);
edtxt2.setText(null);
edtxt3.setText(null);
break;
case R.id.addNextBtn2:
//What does this button do
if (jsonArray != null) {
Intent i = new Intent(AddRecipeScreen2.this, AddRecipeScreen3.class);
startActivity(i);
}else
Toast.makeText(mContext, "Please add Ingredients!",
Toast.LENGTH_LONG).show();
break;
}
}

Related

OnClickListener for Dynamically created buttons

I'm new to android Development and I hope you can help me.I created Buttons Dynamically ( Based on the contents of my Database). I also made onclicklistener for those buttons. The problem now is, If I click the buttons, Nothing happens. There is also no error shown in logcat. Why do you think this happened? Any response will be appreciated.
Here is my code on creating buttons:
final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
cursorCol = scoresDataBaseAdapter.queueCrit(mRowId);
for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
int Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("_id")));
Log.i("_id","_id : "+Id);
String CriteriaButton = cursorCol.getString(cursorCol.getColumnIndex("Criteria"));
Log.i("CriteriaButton","CriteriaButton : " + CriteriaButton);
Button btn = new Button(this);
btn.setText(" " + CriteriaButton + " ");
btn.setId(Id);
btn.setTextColor(Color.parseColor("#ffffff"));
btn.setTextSize(12);
btn.setPadding(10, 10, 10, 10);
btnlayout.addView(btn,params);
btn.setOnClickListener(getOnClickDoSomething(btn));}
Now after my OnCreate, I have the following method to set the onclicklistener
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
String criteria = button.getText().toString();
if ("Exams".equals(criteria)){
Toast.makeText(getApplicationContext(),"Exams Selected",2).show(); }
else if ("Quizzes".equals(criteria)){
Toast.makeText(getApplicationContext(),"Quizzes Selected",2).show(); }
}
};
}
Change
String criteria = button.getText().toString();
to
String criteria = button.getText().toString().trim();
Inside onClick method use View parameter of onClick method to get Text from pressed button as:
public void onClick(View v) {
Button button = (Button)v;
String selectedText = button.getText().toString();
....your code here
}

OnClick button ,create a layer in the same form. Android

I m very new to Android.
I want to create a dynamic OnClick button functionality.
OnClick of "+" above , it should create a other layer , like this below.
My confusion , my entire design UI is in layout.xml.
How we can we include another layer in our UI on OnClick of "+" button.
Any input would be helpful.
Thanks !!!
You could do this programatically. XML is for static layouts.
Excuse my pseudo Android:
private LinearLayout root;
public void onCreate(Bundle b){
LinearLayout root = new LinearLayout(this);
root.addChild(createGlucoseReadingView());
setContentView(root);
}
private View createGlucoseReadingView() {
LinearLayout glucoseRoot = new LinearLayout(this);
glucoseRoot.addChild(new TextView(this));
return glucoseRoot;
}
public void onPlusClick(View button){
root.addChild(createGlucoseReadingView());
}
Something along those lines, I've obviosuly left out formatting and adding the layout params to the views, but you get the idea.
In your XML have one Vertical Linear Layout to add and remove EditTexts at runtime, Here I have shown you code I have used in my demos. To handle and maintain the usage.
Onclick of your Add and Minus button click
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnadd:
createTextview(counter);
counter++;
if (counter > 3) {
btnAdd.setVisibility(View.GONE);
btnRemove.setVisibility(View.VISIBLE);
}
break;
case R.id.btnremove:
removeView(counter);
txtoption[counter - 1] = null;
counter--;
if (counter < 3) {
btnAdd.setVisibility(View.VISIBLE);
btnRemove.setVisibility(View.GONE);
}
break;
}
}
Functions to create and remove view
private void createTextview(int index) {
txtoption[index] = new EditText(this);
txtoption[index].setSingleLine(true);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
param.bottomMargin = 10;
txtoption[index].setLayoutParams(param);
txtoption[index].setBackgroundResource(R.drawable.textbox);
txtoption[index].setTypeface(ttfDroidSherif);
lnpolloptions.addView(txtoption[index]);
}
private void removeView(int index) {
lnpolloptions.removeView(txtoption[index - 1]);
}
Your vertical LinearLayout to contain all the edittext childs
LinearLayout lnpolloptions = (LinearLayout) findViewById(R.id.lnpolloptions);
Arrays of edittext to be created of removed at runtime
private EditText[] txtoption = new EditText[4];
Onclick of submit to get value from each textbox
int length = txtoption.length;
for (int i = 0; i < length; i++) {
if (txtoption[i] != null) {
Log.i("Value",""+txtoption[i].getText());
}
}

dynamic button onclick event inside for loop

i'm using this code to create dynamic buttons within for loop..
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
for (int i=0 ; i<10; i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
TextView textview = new TextView(this);
textview.setText("Text view" + i);
textview.setId(i);
l.addView(textview);
Button button = new Button(this);
button.setText("View");
button.setId(i);
button.setWidth(90);
button.setHeight(60);
l.addView(button);
linearLayout.addView(l);//if you want you can layout params linearlayout
}
now i want to add onclick event to each button based on the iterating i value.. can any one suggest me how to implement this... thanks in advance..
create an arraay of buttons...
Button[] buttons=new Button[10];
and instead of this line
Button button = new Button(this);
in your for loop..use
button[i] = new Button(this);
and in the same loop set your onclicklistener like this..and based on the question you were asking add onclick event to each button based on the iterating i value i think you have same onclicklistener for all buttons..
button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//your onclicklistener code
}
});
Create a List of Button's then add each Button to that list after its created...
List<Button> list = new ArrayList<Button>();
for (int i=0 ; i<10; i++){
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.HORIZONTAL);
TextView textview = new TextView(this);
textview.setText("Text view" + i);
textview.setId(i);
l.addView(textview);
Button button = new Button(this);
button.setText("View");
button.setId(i);
button.setWidth(90);
button.setHeight(60);
l.addView(button);
linearLayout.addView(l);//if you want you can layout params linearlayout
list.add(button);
}
Then use advanced for loop to iterate through the list and add click listener for each Button..
for(Button btn : list){
btn.setOnClickListener(this);
}
Outside your loop create a new View.OnClickListener:
OnClickListener ocl = new OnClickListener(){
#Override
public void onClick(View v){
switch(v.getId()){
case 1:
// click action
break;
case 2:
// click action
break;
}
// ...etc
}
}
Based on the ID of your button, in this case the iteration of i, you can perform various actions. This can be anything, however, like an if...else block on the text of the button or a tag you set.
Then inside your loop, before you addView(l), assign it:
button.setOnClickListener(ocl);
add button.setOnClickListener(this); in the forloop
and add these code below oncreate():::
#Override
public void onClick(View v){
switch(v.getId()){
case 0:
// click action for first btn
break;
case 1:
// click action for 2nd btn
break;
soon upto
case 9:
// click action for 9th btn
break;
}
}
also ypur activity must implement onClickListerner.

How to TextView array

I need to create one textview array, i'd like to show or hide one image depending position.
I'll try to explain it:
I've one layout similar this:
1 2 3 4 5
And depending random value show or hide an image in textview 1 or 2, etc...
I can use:
if (a == 4)
{
t4.setBackgroundResource(R.drawable.ficha);
t1.setBackgroundDrawable(null);
t2.setBackgroundDrawable(null);
t3.setBackgroundDrawable(null);
t5.setBackgroundDrawable(null);
}
else if (a==5)
...
..
But i'd like to know, if it's possible to pass the number t(1) using parameters or something similar.
Thanks in advance and sorry about my english.
you can create textview array like this...
TextView tv[];
tv = new TextView[5];
and you can use Switch Case to show or hide the image...
Have a look at the following snippet;
/*
* Initializes the textViewArray
* You can call this from onCreate.
*/
private void setViews() {
// Declared at class level as private TextView[] textViewArray = null;
textViewArray = new TextView[3];
textViewArray[0] = (TextView) findViewById(R.id.infoText0);
textViewArray[1] = (TextView) findViewById(R.id.infoText1);
textViewArray[2] = (TextView) findViewById(R.id.infoText2);
// Button to demonstrate the functionality
switchButton = (Button) findViewById(R.id.switchButton);
switchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(imgIndex >= textViewArray.length) {
imgIndex=0;
}
showTextViewImage(imgIndex++);
}
});
}
/*
* Sets the background image only for the textView specified by index
*/
private void showTextViewImage(int index) {
setTitle("" + index);
// First remove the backgroud images from all textviews
for(TextView textView : textViewArray) {
textView.setBackgroundDrawable(null);
}
// If you are using a common image for all textViews, use this
textViewArray[index].setBackgroundResource(R.drawable.ficha);
// If you are using different image for every textView, then use this.
/*
switch (index) {
case 0:
textViewArray[0].setBackgroundResource(R.drawable.ficha0);
break;
case 1:
textViewArray[1].setBackgroundResource(R.drawable.ficha1);
break;
case 2:
textViewArray[2].setBackgroundResource(R.drawable.ficha2);
break;
...
...
...
}
*/
}
Hope, you got the idea.
Or you can use List<TextView> tvList = new ArrayList<TextView>();
add as many textviews as you like
and this will retrieve a textview and set background from a list depending on your a value :
((TextView)tvList.get(a)).setBackgroundResource(R.drawable.ficha+a.....);
1st 2nd and so on. you can use Arrays too of course for this purpose.
hope it helps abit

Dynamically creating Buttons and setting onClickListener

I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.
for (int i = 0; i < NO_BUTTONS; i++){
Button btn = new Button(this);
btn.setId(2000+i);
...
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.
#Override
public void onClick(View v) {
switch (v.getId()){
case 2000: selectButton(0);
break;
...
case 2007: selectButton(7);
break;
}
}
This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?
You could create a method that returns an onclickListener and takes a button as a parameter. And then use that method to set the onClicklistener in the first loop you have..
Update: code could be soemthing along these lines:
View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
}
};
}
as a method in the activity and then use it in the loop like this
button.setOnClickListener(getOnClickDoSomething(button));
I got one solution for this..
use this code in onCreate
linear = (LinearLayout) findViewById(R.id.linear);
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
Button[] btn = new Button[num_array_name.length];
for (int i = 0; i < num_array_name.length; i++) {
btn[i] = new Button(getApplicationContext());
btn[i].setText(num_array_name[i].toString());
btn[i].setTextColor(Color.parseColor("#000000"));
btn[i].setTextSize(20);
btn[i].setHeight(100);
btn[i].setLayoutParams(param);
btn[i].setPadding(15, 5, 15, 5);
linear.addView(btn[i]);
btn[i].setOnClickListener(handleOnClick(btn[i]));
}
after onCreate create one method of return type View.OnClickListener like this..
View.OnClickListener handleOnClick(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
}
};
}
Button.OnClickListener btnclick = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button button = (Button)v;
Toast.makeText(getApplicationContext(), button.getText().toString(),2).show();
}
};
call this listener by btn.setOnClickListener(btnclick);
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.
Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().
instead use setTag() function to distinct easily.
for(int i=0;i<4;i++) {
Button btn = new Button(this);
btn.setTag(i);
btn.setOnClickListener(new View.OnclickListener() {
#Override
public void onClick(View v) {
int i=v.getTag();
switch(i) {
case 1: btn.setText(i);
break;
case 2: btn.setText(i);
break;
case 3: btn.setText(i);
break;
case 4: btn.setText(i);
break;
default: btn.setText("Others");
}
}
}
"This doesn't look good to me" why not? doesn't it work? You could also create a static member variable holding a list of all added buttons, and then look for the clicked button in that list instead.
I don't know why you would want to create N buttons, it looks like your value of N is greater than 10 at least, if you are not trying to show them all at once (I mean fit all of them into one single screen, no scrolling) you could try to recycle the invisible buttons just like we do for list view using a list view holder. This would reduce your memory footprint and boost performance, and differentiate the buttons based either on the text you set on them or a tag or you can even hold a reference to those small number of buttons.
Is preferable not to mess up with the ids, setTag and getTag methods were designed for that purpose, it's the fast and clean way to set a bunch of button listeners on a dynamic layout
This answer may you help:
https://stackoverflow.com/a/5291891/2804001
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");
}
}

Categories

Resources