Android How to change data of Textview by clicking on button - java

First of all, the app looks like this.
How to make - if I click on Add, on its column the textview is updated with value + 1?
I'm creating TextView and Button in a Loop;
for(int i = 0;i < playercountint; i++)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
????? what here?
}
});
}
What should be written in onClick function , so only TextView value which is in buttons column is changed.
There is one outer LinearLayout which is horizontally oriented, and those which are created within a loop is vertical Linear Layouts.
Maybe i should create a template for 1 loop iteration?

First make your textview final and them set it's value in onClick
for(int i = 0;i < playercountint; i++)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
final TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tt.setText(String.valueOf(Integer.parseInt(tt.getText())+1));
}
});
}
You can write one function that returns linearlayout:
public View getPlayerView(){
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,(100/playercountint)));
layout.setGravity(Gravity.CENTER_HORIZONTAL);
final TextView tt = new TextView(this);
tt.setText("0");
tt.setTextSize(14);
tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tt.setGravity(Gravity.CENTER_HORIZONTAL);
Button btadd = new Button(this);
btadd.setText("Add");
btadd.setId(2);
btadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tt.setText(String.valueOf(Integer.parseInt(tt.getText())+1));
}
});
layout.add(tt);
layout.add(btadd);
return layout;
}
Call this function in a loop.

tt.setText("something");
tt.invalidate();
my bad I didn't even notice it was a for loop uh you need to hold a reference to the text view.. make your textview final

tt.setText(Integer.parse(tt.getText().toString()) + 1);
But, I strongly recommend you design UI (layout) in the *.xml file!
See more: http://developer.android.com/guide/topics/ui/declaring-layout.html

You should provide your TextView with an unique id (.setId(...)). Having this, in your onClick method simply use something like this:
final TextView tv = (TextView) findViewById(R.id.your_textview_id);
final String cur_text = tv.getText();
Integer plus_one = Integer.valueOf(cur_text);
plus_one++;
tv.setText(plus_one.toString());
Didn't try it but should work.

static int counter = 0;
btn_Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter ++;
tv_Display.setText("Your Total is : " + counter);
}
});

Related

How to remove dynamically created imageview from another button onclick?

I have created an ImageView dynamically like below image.It works fine. Now I want to remove view when top cross ImageView is clicked. When I click, it crashes .Please help how to achieve it.
here is what i have done
private void postImage(List<Uri> urilist) {
for(int i=0; i< urilist.size(); i++) {
imgView = new ImageView(getActivity());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(150, 150);
lp.setMargins(20,10,20,10);
imgView.setLayoutParams(lp);
imgView.setId(i);
Log.d("uri list in loop",""+urilist.get(0));
Glide.with(getActivity())
.load(urilist.get(i))
.into(imgView);
layout.addView(imgView);
imgView1 = new ImageView(getActivity());
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(50, 50);
lp1.setMargins(0,5,1,80);
imgView1.setLayoutParams(lp1);
imgView1.setId(i);
Log.d("uri list in loop",""+urilist.get(0));
Glide.with(getActivity())
.load(R.drawable.ic_action_cross)
.into(imgView1);
layout.addView(imgView1);
}
imgView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeViewAt(v.getId());
}
});
}
If it is because of the index (which definitely will crash in deletion of the 2nd item) then you can try below
imgView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewGroup parentView = (ViewGroup) v.getParent();
parentView.removeView(v);
}
});
Note: You should not set id of two views as same. Rather use some mathematical formula.
I mean #shakac, you can try like that;
for(int i = 0; i<layout.getChildCount(); i++)
{
if (layout.getChildAt(i).getId() == v.getId()){
layout.removeView(layout.getChildAt(i));
break;
}
}
But as I said on the comment, you will remove the cross button like that.

Having trouble removing and then adding views programatically to FrameLayout

I am having trouble removing a LinearLayout from a FrameLayout, to then add a new LinearLayout that is populated with EditText generated programatically.
The first time that the view is loaded, I catch a reference to the FrameLayout using findViewById(), and then I make a new LinearLayout programmatically and add a number of EditText to it.
It looks like this
formPlace = (FrameLayout) findViewById(R.id.form_place);
LinearLayout linearView = new LinearLayout(this);
linearView = makeEditText(arrayItems,category);
linearView.setBackgroundColor(Color.GRAY);
linearView.setOrientation(LinearLayout.VERTICAL);
formPlace.addView(linearView);
Next is the function that makes the EditTexts:
private LinearLayout makeEditText(ArrayList<String[]> arrayString, int position){
LinearLayout view = new LinearLayout(this);
arrayInputs = new ArrayList<>();
String[] arrayHints = arrayString.get(position);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
for (int i=0;i<arrayHints.length;i++){
EditText editText = new EditText(this);
Log.i("myApp","tantas veces" + i);
editText.setId(i);
editText.setTextColor(Color.BLACK);
editText.setHint(arrayHints[i]);
editText.setHintTextColor(Color.GRAY);
editText.setLayoutParams(params);
view.addView(editText);
arrayInputs.add(editText);
}
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonParams.gravity = Gravity.RIGHT;
android.widget.Button save = new android.widget.Button(this);
save.setText("Guardar");
save.setLayoutParams(buttonParams);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("myApp", "guardar");
saveClicked(category);
}
});
view.addView(save);
android.widget.Button cancel = new android.widget.Button(this);
cancel.setText("cancelar");
cancel.setLayoutParams(buttonParams);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("myApp", "cancelar");
cancelClicked();
}
});
view.addView(cancel);
return view;
}
Then, when a spinner event is called, I catch the reference of the FrameLayout and pass .removeAllViews(). This works as intended, and my pevious view is deleted. The problem comes when I try to add new views to the FrameLayout in the makeEditText line:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
if(firstTime==false) {
FormActivity.this.formPlace.removeAllViews();
LinearLayout auxLinearView = new LinearLayout(FormActivity.this);
auxLinearView = makeEditText(arrayItems, position);
FormActivity.this.formPlace.addView(auxLinearView);
}
firstTime =false;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
What happens is that the old view is deleted but the new view is not set properly. It only shows 1 element of the 4 is intended to show, and the buttons that I create programmatically don't show at all. And my FrameLayout occupies all the remaining space in my screen, even though is set to wrap content. What it implies is that the view is not behaving as it should.
EDIT:
Here are some Screenshots
Here is how it looks before removeAllViews():
https://dl.pushbulletusercontent.com/tExAXJexe4BfG5sGuKvb1RFtGOFd51nE/Screenshot_2015-05-04-17-54-18.png
Here is how it looks after adding the views to the FrameLayout:
https://dl.pushbulletusercontent.com/JM72D3ZrLwTh0YC9g7PODREyOfCj667P/Screenshot_2015-05-04-17-54-25.png

How to set onClickListener for the textviews generated dynamically?

Can anyone please guide me on how to setOnClickListener for the TextViews that are generated dynamically.
I have few buttons in my app.Now when a particular button is clicked than some specific text elements are retrieved from the database based on the the number of elements returned corresponding TextViews are generated in order to display the retrieved text elements.
Now the problem that i'm having is that i don't know how to set onClickListner for the dynamically generated TextViews.Following is the piece of code where i'm creating my TextViews.Please guide me on what should i do.thank you
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
catagory = "General";
IndependentDB genData = IndependentDB.getInstance();
genData.open(this);
ArrayList<TextHolder> genList = new ArrayList<TextHolder>();
genList = genData.getAllTextFromGenT();
genData.close();
x = genList.size();
String xstr = new StringBuilder().append(x).toString();
System.out.println(xstr);
mainText = new TextView[x];
textLayout = new LinearLayout[x];
llseperator = new LinearLayout[x];
textLayoutContainer
.setBackgroundResource(R.color.dark_navy_blue);
if (!genList.isEmpty()) {
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setId(i);
mainText[i].setText("Text");
mainText[i].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mainText[i].setTextSize(25);
mainText[i].setGravity(Gravity.CENTER);
mainText[i].setText(text);
mainText[i].setTextColor(0xFFFFFFFF);
mainText[i].setClickable(true);
mainText[i].setOnClickListener(this);
llseperator[i] = new LinearLayout(this);
llseperator[i].setId(i);
llseperator[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
llseperator[i].setGravity(Gravity.CENTER);
llseperator[i]
.setBackgroundResource(R.drawable.tv_seperator);
textLayout[i] = new LinearLayout(this);
textLayout[i].setId(i);
textLayout[i].setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
textLayout[i].setGravity(Gravity.CENTER);
textLayout[i].addView(mainText[i]);
textLayoutContainer.addView(textLayout[i]);
textLayoutContainer.addView(llseperator[i]);
}// End of for
}// End of If
break;}
You already have onClick() method in Activity class (implemented View.setOnClickListener) so I suggest you to create a new class which implements View.setOnClickListener interface to handle click of TextView.
Try,
class TextClick implements View.setOnClickListener {
#Override
public void onClick(View view) {
TextView tx=(TextView) view;
...
}
}
and set click listener,
TextClick click=new TextClick();
for (int i = 0; i < x; i++) {
TextHolder firstOne = genList.get(i);
String text = firstOne.getText();
mainText[i] = new TextView(this);
mainText[i].setOnClickListener(click);
...
}
It's the same setting on click listeners regardless of if the view was dynamically generated.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dosomething();
}
});
For example. you have a List tvs to store your TextView Objects created by the db result. What you should do is like this:
for(int i =0;i<tvs.count;i++){
tvs.get(i).setOnClickListener(new OnClickListener(){
...
})
}

Question about arrays and buttons in eclipse + android java project

well im kind of new to eclipse anyways i was wondering is there a way for me to create an array of buttons in the java code rather then a xml file, then define there positions on the layout.
Every Button object is a view itself. Therefore, it can be added to a parent Layout (like the LinearLayout). The easiest way IMHO is creating the XML only for the things you know that will not change, or maybe using a TableLayout. Then, add the buttons.
LinearLayout mainLayout = findViewById(R.id.mainLayout);
Button[] btnArray = new Button[3];
for(Button button : btnArray){
button = new Button(/*Required params */);
// button.something , play with text and onclick and positions...
mainLayout.addView(button);
}
Is this what you're trying to do?
LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}

Create a new TextView programmatically then display it below another TextView

String[] textArray={"one","two","asdasasdf asdf dsdaa"};
int length=textArray.length;
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int i=0;i<length;i++){
TextView tv=new TextView(getApplicationContext());
tv.setText(textArray[i]);
relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
layout.addView(tv, relativeParams);
}
I need to do something like that.. so it would display as
one
two
asdfasdfsomething
on the screen..
If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.
Complete code:
String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for( int i = 0; i < textArray.length; i++ )
{
TextView textView = new TextView(this);
textView.setText(textArray[i]);
linearLayout.addView(textView);
}
Try this code:
final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];
for (int i=0; i<str.length; i++)
{
tv[i] = new TextView(this);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin = 50;
params.topMargin = i*50;
tv[i].setText(str[i]);
tv[i].setTextSize((float) 20);
tv[i].setPadding(20, 50, 20, 50);
tv[i].setLayoutParams(params);
rl.addView(tv[i]);
}
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
#Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).
You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

Categories

Resources