How to remove dynamic button on android studio - android

I add some button with image and animation in my code, the following is my code.
//add diamond to relativelayout
private void addDiamond(){
Drawable img = getContext().getResources().getDrawable( R.drawable.diamond );
img.setBounds( 0, 0, diamondWidth, diamondHeight );
for (int i = 0; i < diamondRow; i++) {
LinearLayout row = new LinearLayout(getContext());
row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
diamondHeight+120));
for (int j = 0; j < diamondCol; j++) {
Button btnTag = new Button(getContext());
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
btnTag.setCompoundDrawables(null, img, null, null);
btnTag.setText("0.0158" + (j + 1 + (i * diamondCol)));
btnTag.setTextColor(Color.WHITE);
btnTag.setTextSize(8);
btnTag.setBackgroundColor(Color.TRANSPARENT);
btnTag.setId(j + 1 + (i * diamondCol));
btnTag.setOnClickListener(btnClick);
row.addView(btnTag);
}
diamond_lyt.addView(row);
}
animate(diamond_lyt);
}
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Now I wnat to click these button to remove it individually.
But it is very strange in the result.
When I click two column first button, it remove two column last button.
Please how can I solve this problem?

There's nothing wrong with the click, it removes the views correctly as you click on them. I guess whenever you remove a button, the remaining buttons in the row shift towards left creates an illusion which makes you think it removes the wrong button.
If you intend to have a grid-like layout, that the buttons should always stay in their positions on screen, you could try setting the visibility to View.INVISIBLE instead of removing the view, or replace it with an empty view of the same size.

This one too simple.....
Instead of this ...
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button = diamond_lyt.findViewById(v.getId());
Toast.makeText(getContext(), String.valueOf(button.getId()), Toast.LENGTH_SHORT).show();
ViewGroup layout = (ViewGroup) button.getParent();
layout.removeView(button);
}
};
Try this one ....
private Button.OnClickListener btnClick = new Button.OnClickListener(){
public void onClick(View v){
Button button =((Button)v);
((ViewGroup) button.getParent()).removeView(button);
}
};
When Your button click onClick(View v) v give you instance of button. TypeCaste from View to Button and remove it.

Related

Find child of a LinearLayout inside a LinearLayout

I have a LinearLayout ("ll") that is already created in xml and the app dynamically creates another LinearLayout inside of it and creates an EditText and a Button inside of that view. The button makes the whole LinearLayout destroy itself along with the EditText and Button inside it (the whole system is a player name entering activity). Anyway, I am trying to find a way to get the text from all of the EditTexts. I have tried using a for loop on "ll" and using ll.getChildAt() but I can't seem to use .getChildAt() on whatever ll.getChildAt() generates because getChildAt() generates a "View" not a "LinearLayout." I basically just need a way to search two children in, rather than just one. Also, if there is just a better way I should be doing this, let me know. I'm open to suggestions.
Here's my code if it will help:
NewGameCreate.java
public class NewGameCreate extends Activity {
int numOfPlayers = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_game_create);
}
public void newPlayer(View view) {
numOfPlayers++;
final LinearLayout ll = findViewById(R.id.playerView);
final LinearLayout llNew = new LinearLayout(getApplicationContext());
llNew.setOrientation(LinearLayout.HORIZONTAL);
llNew.setId(numOfPlayers);
ll.addView(llNew);
EditText newName = new EditText(this);
newName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
newName.setHint("Enter Player Name");
newName.setId(numOfPlayers);
newName.setWidth(0);
llNew.addView(newName);
final Button delete = new Button(this);
delete.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
delete.setText("Delete");
delete.setId(numOfPlayers);
delete.setWidth(0);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = delete.getId();
ll.removeViewInLayout(findViewById(id));
Drawable back = ll.getBackground();
ll.setBackgroundColor(00000000);
ll.setBackground(back);
ll.invalidate();
}
});
llNew.addView(delete);
}
public void startGame(View view){
LinearLayout ll = findViewById(R.id.playerView);
List text = new ArrayList();
for(int loop = 0; loop < ll.getChildCount(); loop++) {
//this is the code in question and where I want to get the text from
//all my EditTexts
LinearLayout inner = ll.getChildAt(loop);
}
}
}
I think I found the answer to it. You need to change a little bit of code in the startGame() method I m providing the code for startGame below.
public void startGame(View view) {
LinearLayout ll = findViewById(R.id.playerView);
List text = new ArrayList();
for (int loop = 0; loop < ll.getChildCount(); loop++) {
//this is the code in question and where I want to get the text from
//all my EditTexts
LinearLayout inner = (LinearLayout) ll.getChildAt(loop);
for (int j = 0; j < inner.getChildCount(); j++) {
if (inner.getChildAt(j) instanceof EditText) {
EditText textET = (EditText) inner.getChildAt(j);
Log.d("TAG",textET.getText().toString());
}
}
}
}
In the above code you were able to get the first child only but as you have added a linearLayout with orientation Horizontal in a parent LinearLayout with orientation Vertical, you have written code for the child of parent layout i.e playerView. I have modified the code to get the elements of the child Linear layout and Log prints all the text from the EditText.
Hope that helps!!

Android Dynamic Button - Same arithmatic operator displayed again and again and also not formatted - Its worked

I am new to android. I want to display the 5 numbers in the Button. And also needs to display the arithmetic buttons also like below
14 12 13 12 11 ( These number to be displayed in the button )
+ - * / ( These arithmetic button also displayed in button)
I want to display like above dynamically. And i am using this code, but it displaying like below.( not displaying +, - *, / )
/ 14
/ 12
/ 13
/ 12
/ 11
I want to display like mentioned initially and also i want listen the button clicked
Its displaying Normal buttons, how i can display as like Graphic buttons. ( so that it will give more attraction)
Please find the code below.
setContentView(R.layout.dynamically_create_view_element);
final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
// create the layout params that will be used to define how your
// button will be displayed
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int j=0;j<5;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
final Button btn1 = new Button(this);
// Give button an ID
btn1.setId(1);
btn1.setText("+");
btn1.setId(2);
btn1.setText("-");
btn1.setId(3);
btn1.setText("*");
btn1.setId(4);
btn1.setText("/");
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
int random1 = (int )(Math.random() * 20 + 1);
btn.setText(""+numbers[j]+"");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Create four
//Add button to LinearLayout
ll.addView(btn1);
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
Ok there are multiple issues with your code:
First, you're getting the below result
/ 14
/ 12
/ 13
/ 12
/ 11
because inside your for-loop you're setting the text of btn1 to / after setting the text of the Button to + then to - and then to *.
Also because you're creating a LinearLayout for each Button you're getting the numbers below each other.
I've taken the liberty to re-write the code a bit into something a bit more generic:
public class MainActivity extends Activity {
private LinearLayout lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LinearLayout) findViewById(R.id.lm);
// Create a LinearLayout for each row inside the outer LinearLayout.
LinearLayout firstRow = new LinearLayout(this);
firstRow.setOrientation(LinearLayout.HORIZONTAL);
// Create a String array of items you want to add to the inner LinearLayout.
String[] itemsToAddToFirstRow = { "14", "12", "13", "12", "11" };
createButtonsDynamically(firstRow, itemsToAddToFirstRow);
String[] itemsToAddToSecondRow = { "+", "-", "*", "/" };
LinearLayout secondRow = new LinearLayout(this);
secondRow.setOrientation(LinearLayout.HORIZONTAL);
createButtonsDynamically(secondRow, itemsToAddToSecondRow);
}
private void createButtonsDynamically(LinearLayout layoutToAddButtonsTo, String[] itemsToAdd) {
for (int i = 0; i < itemsToAdd.length; i++) {
final Button buttonToAdd = new Button(this);
buttonToAdd.setText(itemsToAdd[i]);
buttonToAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "I was clicked: " + buttonToAdd.getText(), Toast.LENGTH_SHORT).show();
}
});
layoutToAddButtonsTo.addView(buttonToAdd);
}
// In the end add all buttons inside the inner LinearLayout to the outer LinearLayout.
lm.addView(layoutToAddButtonsTo);
}
}
Add your own code to add the ids to the Buttons.
The end-result will look like this:
As far as your #2. goes:
You could a background image to your Buttons by calling setBackground(Drawable drawable) for the buttons or you completely re-style the standard Button.
Have a go at this guide from the official guidelines.
Hope this helps :-)

How to remove a Button added programatically

I am adding buttons to a linear layout at runtime and need to add the functionality of removing them if the user desires. At the moment I have a button which opens a popup with a list consisting of the text for each button added. If possible, would I be able to have each onItemClick delete the corresponding button? If not, what would be the best way to remove a specific button?
Here is the code for adding buttons:
private void addButton(){
LinearLayout lL = (LinearLayout) findViewById(R.id.requirement_linear);
lL.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0,2,0,0);
Button b = new Button(this);
b.setBackgroundResource(R.drawable.blue_button);
b.setOnClickListener(openRequirement);
b.setTextColor(Color.parseColor("#FFFFFF"));
String button_text = (index + 2) + ". " + requirement_list.get(index + 1).getName();
b.setText(button_text);
requirements_text.add(button_text);// requirements_text is an arraylist<string> which stores the text so I can display them in my popup to delete them.
index ++;
lL.addView(b,p);
}
You can use removeView() on your LinearLayout and pass your button. You can identify the button on the OnClick(View view) callback, the view there is the button.
as requested, here is an example.
final LinearLayout lL = (LinearLayout) findViewById(R.id.requirement_linear);
Button b = new Button(this);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View button) {
lL.removeView(button);
}
});
lL.addView(b);
Alternatively you can use removeViewAt() to remove a child view by index. You can use the index of your 'list of text of buttons'. Assuming its a listview, you can try this.
lview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
lL.removeViewAt(position);
}
});
here is how i hide and show the buttons
Button b = new Button(this);
b.setVisibility(View.GONE); // this will hide the button and it will now show
b.setVisibility(View.VISIBLE); // this will show the button if it was hidden before
Enjoy!

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

Removing Layout on a button clilck

I am working on android.And i was creating an application in which i dynamically created a group of buttons on a button click.But what happens is buttons are created every time i click the button.i want this to happen once.Can i clear the space just at the beginning of OnClickListener()? i dunno how to do it.Below is my code.
button_generate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//*-----------clearing the variables--------*
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
int k=0,i=0,j=0;
count=3;
System.out.println("count is"+count);
while(j<count)
{
TableRow tr = new TableRow(EspeakerActivity.this);
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
rel.addView(tr);
}
j++;
}
}
}
);//*--------closing the button click------*
Give the buttons ID's and then use findViewByID() to see if the buttons already exist before adding them.
TableRow tr = new TableRow(EspeakerActivity.this);
tr.setId(/*some id*/)
//for(int c=1; c<=3; c++) {
Button b1 = new Button (EspeakerActivity.this);
Button b2= new Button (EspeakerActivity.this);
Button b3 = new Button (EspeakerActivity.this);
b1.setText("1");
b2.setText("2");
b3.setText("3");
b1.setTextSize(10.0f);
200));
tr.addView(b1, 100,50);
tr.addView(b2, 100,50);
tr.addView(b3, 100,50);
//check rel already has that tr.. if it has don't add anythin.. better if you do it before even creating the TAbleRow
rel.addView(tr);
Hiding linear layout on runtime in Android
you can refer the link and i am sure you will get your ans.if not solve through this link
then tell me.
You can clear your TableLayout on each button click as follows
....
onClick(View v) {
final TableLayout rel=(TableLayout)findViewById(R.id.tab1);
for(int x=0; x<rel.getChildCount(); x++)
{
View v = rel.getChildAt(x);
rel.removeView(v);
}
....
}

Categories

Resources