10.DYNAMIC BUTTON
So far we have been using button by adding them in xml then binding it
with button in activities. But times may come when we need to add them
dynamically. In such cases we define them, buttons, in activities and add them
to layouts as shown below
package a.b.c;
import android.app.Activity;
import
android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import
android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import
android.widget.CompoundButton;
import
android.widget.CompoundButton.OnCheckedChangeListener;
import
android.widget.LinearLayout;
import
android.widget.ScrollView;
import android.widget.Toast;
public class
DynamicbuttonActivity extends Activity {
Button b;
ScrollView scrollview;
/** Called when the activity is first created. */
@Override
public void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scrollview = new
ScrollView(this);
LinearLayout
linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearlayout);
for(int i = 0;
i<15;i++)
{
LinearLayout linear1 = new LinearLayout(this);
linear1.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linear1);
b = new Button(this);
b.setText("Button
no "+i);
b.setId(i);
b.setTextSize(10);
b.setPadding(8, 3, 8, 3);
b.setTypeface(Typeface.SERIF,Typeface.BOLD_ITALIC);
b.setLayoutParams(new
LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
linear1.addView(b);
CheckBox checkbox = new CheckBox(this);
checkbox.setId(i);
checkbox.setText("Wow..");
linear1.addView(checkbox);
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void
onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Checked.."+ arg0.getId(), Toast.LENGTH_SHORT).show();
}
});
b.setOnClickListener(new View.OnClickListener() {
@Override
public void
onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Yipee.."+ v.getId(), Toast.LENGTH_SHORT).show();
}
});
}
this.setContentView(scrollview);
}
}
|
Gayet güzel paylaşım, teşekkürler.
ReplyDeleteThank you sir :)
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteVery usefull, but I have one question. I need to use those buttons IDs so I can define what to do when I click on them. I know how to do onClick method when I write buttons in XML, but from here I can't. Can anyone help me?
ReplyDeleteCodes to Generate more Buttons from the two Dynamically Generated Buttons-
ReplyDeleteplease help me to do programmatic work in an android studio i;e..to Generate Two Buttons which will be a BAR and a RESTAURANT and On Clicking that two buttons i would like to generate n numbers of dynamic buttons.
Hoping forward to get your help to build my App.
Thank you.