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
}
Related
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.
I'm trying to add some buttons at runtime and want to assign an OnClickListener that triggers the start of a new activity.
But I get a The constructor Intent(new View.OnClickListener(){}, Class<CollectionDemoActivity>) is undefined error in my IDE Editor.
While startActivity(new Intent(this,CollectionDemoActivity.class)); is accepted from the IDE and works fine when I call it from e.g. the onStart() Method
But I need the buttons dynamically created..... What am I doing wrong? What is the the best alternative for this?
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
for (int i = 1; i <= 10; i++) {
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("_button " + id_);
btn.setBackgroundColor(Color.GREEN);
ll.addView(btn, params);
Button btn1 = ((Button) ll.findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(this,CollectionDemoActivity.class));
}
});
this inside the anonymous OnClickListener refers to to exactly this surrounding class, not to the Activity. Assuming the Activities name is MyActivity, change this to MyActivity.this or getContext()
I've stored the imagebutton info in an xml. It's image path,width,height and so on.
But since there are multiple images I want to store data for each imagebutton while it's clicked. for example, if there are two buttons named male and female, i want to set String value = "male"; if male image button is clicked. But it did not work. Can somebody help me?
public void AddAllImageButtons() throws IOException {
AbsoluteLayout Layout = (AbsoluteLayout) findViewById(R.id.layout1);
ImageButton btn = new ImageButton(this);
Layout.addView(btn);
AbsoluteLayout.LayoutParams absParams = (AbsoluteLayout.LayoutParams) btn
.getLayoutParams();
absParams.x = x;
absParams.y = y;
btn.setLayoutParams(absParams);
btn.setBackgroundDrawable(null);
btn.setImageBitmap(BitmapFactory.decodeStream(getAssets().open(path)));
if(type.equals("imagebutton")){
if(elementId.equals("female")){
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gender = elementId;
GenerateAlertBoxes(gender);
}
});
}
Id is the image button id which is created in xml file.
AlertBox text does not show "female" for this example.
you can setTag("value") to set the value in the ImageButton btn and on the onclick event you can use getTag() function to retrieve the value and set it to gender.
use btn.setTag(elementid); whenever you add a btn to the layout.......
inside btn.setOnClickListener you can write v.getTag().toString() to get the value and set it to gender......
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gender = v.getTag().toString();
GenerateAlertBoxes(gender);
}
});
public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(getActivity());
ll.addView(btn);
btn.setLayoutParams(params);
btn.setOnClickListener(o);
ly.addView(ll);
i++;
}
I wrote the above code to create the textfields and buttons dynamically; But now I need to remove 2 textfields and a button when the button is clicked. How do I do that?
Try following code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LinearLayout linearParent = (LinearLayout) v.getParent().getParent();
LinearLayout linearChild = (LinearLayout) v.getParent();
linearParent.removeView(linearChild);
}
});
Explanation
Here first take "GrandParent" of any view.
Then take its "Parent" view
With reference to "GrandParent" remove that "Parent" view.
this will remove all views which that "Parent" holds. As per your code, your "ll" will be "linearChild" here. And "ly" will be "linearParent" here. So whole "ll" will be removed from "ly" which you have added dynamically.
If you want to permanently remove the views you created.
OnClick(View view){
ly.removeAllViews()
}
If you do not want to permanently remove the views you created.
OnClick(View view){
ly.setVisibility(View.GONE); //This will hide the all views
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
So use appropriate code line which you want.
EDIT:
Use this code for your situation:
public void Add_text() {
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(i);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView product = new TextView(getActivity());
product.setText(" Product" + 5 + " ");
ll.addView(product);
EditText qty = new EditText(getActivity());
qty.setText(i + "");
qty.setId(i);
qty.setWidth(120);
ll.addView(qty);
Button btn = new Button(this);
ll.addView(btn);
btn.setLayoutParams(params);
ly.addView(ll);
i++;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View button) {
qty.setVisibility(View.GONE);//This will hide the EditText qty
product .setVisibility(View.GONE);//This will hide the TextView product
}
});
}
i think you got to use this method on your LinearLayout :
public void removeView (View view)
first you call :
EditText et = (EditText)linearLayout.findViewById(yourEditText.getId());
then call the remove view method :
linearLayout.removeView (et) ;
and to remove all of the Views that are in the LinearLayout do the following :
public void removeAllViews ()
like the following :
linearLayout.removeAllViews()
and give me some feedback
Hope that Helps .
you can simply use qty.setVisibility(View.GONE) on the onClickListener() of the Button of your choice. like this.
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
qty.setVisibility(View.GONE); //for temporary purpose
//or u can also do this
layout.removeView(qty); //removes permanently
}
});
The benefit of using View.GONE is that you can get the View back if you want but layout.removeView(qty) will remove the view permanently and you have to re add the view again.
[EDIT] 1. changed to View.GONE instead of View.INVISIBLE because of reasons explained here
Hope I answered your question. :)
just use index for which you want to remove your view from linear layout
Linearlayout.removeViewAt();
if you want again that view then you can call addViewAt()in same way.
I hope it will help you.
Add this line
mLayout.removeViewAt(mLayout.getChildCount()-1);
I'm completely new to Java and android. I ended a tutorial and I'm building a simple calculator to learn the ropes.
I basically have a view like this:
<button android:onClick="addText" android:text="2" />
And function addText is this:
public void addText(View view) { // Add view's text
TextView calc = (TextView) findViewById(R.id.edit_text);
t.setText( calc.getText() + ????? );
}
onclick it should add the text from the clicked button to a TextView. If you click 1, it does calc.getText() + "1" if you click 2 it does calc.getText() + "2". I don't know how to get the clicked view's text. I tried this: t.setText( calc.getText() + this.getText() ); which didn't work. How is this done?
You can do this:
public void addText(View view) { // Add view's text
Button button = (Button) view; //casts the View into the Button class
TextView calc = (TextView) findViewById(R.id.edit_text);
t.setText(calc.getText().toString() + button.getText().toString());
}
Since we know that Button is a subclass of View, and the getText() method works with buttons, we can make a new variable and turn the View parameter into a Button, via class casting. From there we can use all the Button's methods and continue with execution.
Other way is by setting TAG object to your views
Button mButtonCalcOne = (Button) findViewById(R.id.Button1);
mButtonCalcOne.setTag(1);
OnClickListener mButtonListener = new OnClickListener()
{
#Override
public void onClick( View v )
{
int lButtonValue = (Integer) v.getTag(); //DO STH WITH IT ; )
};
}
mButtonCalcOne.setOnClickListener( mButtonListener );