How inflate button dynamically in android [duplicate] - android

I am inflating an xml having button, multiple times and i am able to do so perfectly but the problem is when I click the button,i want to show which button is clicked.
public class InflateExActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button b;
LinearLayout lLayout;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 3; i++) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
t = (TextView) inflater.inflate(R.layout.texts, null);
b.setTag(i); // you'll get 0,1,2 as
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(this);
}
}
public void onClick(View v) {
}
}

You can use setTag() to each button. Inside the for loop you can assign button.setTag(). And you can use getTag() to retrieve button's tag. After you inflate the layout, add a tag to your button
EDIT2:
You should inflate the layout and then look up for your button id. See below:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
final Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.buttons, null);
b = v.findViewById(R.id.your_button_id);
// b = (Button) inflater.inflate(R.layout.buttons, null);
b.setTag(i); // you'll get 0,1,2 as tags
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int specificButton = (Integer)v.getTag();//Changed here.......
Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton),
Toast.LENGTH_LONG).show();
}
});
}
}
}

items you are adding programmatically, you must have to assign ids to them.
b.setId(1);
EDITED:
public class DynamicLayoutActivity extends Activity implements OnClickListener{
private static final int MY_BUTTON = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
}
public void onClick(View v) {
Toast toast;
Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
switch (v.getId()) {
case MY_BUTTON:
toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
LATEST:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
b.setId(i);
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(),
Toast.LENGTH_LONG).show();
}
});
}
}

Use the view tag
View.setTag(Object tag);
You can set a string or a complex object like a class to the tag.

Related

Struggling to replace SPINNER with BUTTONS populated from database

Trying to replace spinner with buttons dynamically populated from database.
Normally spinner use array adapter and built-in List Item Layouts "android.R.layout.simple_spinner_item"etc.
How should it be modified if instead of spinner you want to populate buttons?
Should I replace layouts for spinner in my in loadDifficulties() method with layouts for buttons?
HERE HOW IT WORKED WITH SPINNER
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
spinnerDifficulty = findViewById(R.id.spinner_quizlist);
loadDifficulties();
Button startTest = findViewById(R.id.start_test);
startTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startQuiz();
}
});
}
private void startQuiz() {
ListQuiz selectedLevel = (ListQuiz) spinnerDifficulty.getSelectedItem();
int LevelListID = selectedLevel.getId();
String quizListName = selectedLevel.getName();
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
ArrayAdapter<ListQuiz> adapterLevelList = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, LevelList); adapterLevelList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDifficulty.setAdapter(adapterLevelList);
}
onCreate(){
LinearLayout listOrders = findViewById(R.id.listOrders);
for (int i = 0; i < listForShowing.size(); i++){
String text = listForShowing.get(i);
listOrders.addView(createButton(text));
}
listOrders.requestLayout();
}
public Button createButton(String text){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button button = inflater.inflate(R.layout.button, null);
button.setText(text);
}
Briefly
Created LinearLayout for buttons.
I didn't need to use ArrayAdapter in the loadDifficulties anymore.
Added all needed parameters to startQuiz() (in my case int & String) simplifying method to Intents only.
private ArrayAdapter <ListQuiz> adapter;
private Button autobutton;
public int categorySize;
private List<ListQuiz> categoryName;
private LinearLayout QuizListLayout;
private Button levelButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_screen);
autobutton = findViewById(R.id.autobutton);
loadDifficulties();
QuizListLayout = findViewById(R.id.layoutForButtons);
for(int i=0; i<categorySize;i++){
levelButton =new Button(this);
levelButton.setText("" + categoryName.get(i));
levelButton.setId(i);
final int index = i;
levelButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
levelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startQuiz(v.getId(), categoryName.get(index).toString());
}
});
QuizListLayout.addView(levelButton);
}
}
private void startQuiz(int LevelListID, String quizListName) {
Intent intent = new Intent(StartingScreenActivity.this, MainActivity.class);
intent.putExtra(EXTRA_DIFFICULTY_ID, LevelListID);
intent.putExtra(EXTRA_DIFFICULTY_NAME, quizListName);
startActivityForResult(intent, REQUEST_CODE_QUIZ);
}
private void loadDifficulties(){
QuizDbHelper dbHelper = QuizDbHelper.getInstance(this);
List<ListQuiz> LevelList = dbHelper.getAllListQuiz();
categorySize = dbHelper.getAllListQuiz().size();
categoryName = dbHelper.getAllListQuiz();
buttonlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/layoutForButtons">
</LinearLayout>

i want the value of inflated edittext with other layout using for loop in java

I need the value of inflated editText, I am inflating the design layout which is the child layout and MainActivity is a parent layout.
below is the MainActivity class
public class MainActivity extends AppCompatActivity {
View array[];
String text;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext1 = (EditText) findViewById(R.id.email);
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
text = edittext.getText().toString();
}
edittext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "" + text, Toast.LENGTH_SHORT).show();
}
});
}
}
Here is total code of store object and retrieval,
read all comments please,
public class MainActivity extends AppCompatActivity {
View array[];
String text;
LinearLayout container;
// list of edittext
List<EditText> edtlist = new ArrayList()<EditText>;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edittext1 = (EditText) findViewById(R.id.email);
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
// store object in list
edtlist.add(edittext);
text = edittext.getText().toString();
}
edittext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "" + text, Toast.LENGTH_SHORT).show();
}
});
// call this whenever you want in any event
// here 0 is first edittext
// you can get all text value using for loop
// list.get(0).getText().toString();
}
}
You are looking for something like ,I'm not sure about it maybe it works maybe it wont.! it just a rough concept based code havnt Implemented yet.!
List<EditText> edtxtList;
List<String> edtxtStrList;
for (int i = 0; i < 4; i++) {
LinearLayout myLayout = (LinearLayout) findViewById(R.id.linearlayout);
View v = getLayoutInflater().inflate(R.layout.design, myLayout, false);
myLayout.addView(v);
int id = View.generateViewId();
v.setId(id);
EditText edittext = (EditText) v.findViewById(R.id.edittext);
text = edittext.getText().toString();
edtxtList.add(edittext);// try something like this.!
}
Then use Foreach loop on EditText;
for (EditText edText : edtxtList) {
if(!edText.getText().trim()=null){
edtxtStrList.add(edText.getText().trim());
}
}
I havnt tried It yet but maybe this ruff concept may helps you.!
Maybe this Method helps You.!
ArrayList<EditText> myEditTextList = new ArrayList<EditText>();
for( int i = 0; i < myLayout.getChildCount(); i++ )
if( myLayout.getChildAt( i ) instanceof EditText )
myEditTextList.add( (EditText) myLayout.getChildAt( i ) );
In Above code mLayout is your layout.!
<LinearLayout android:id="#+id/myLinearLayout" >
//Here is where your EditTexts would be declared
</LinearLayout>

How to disable programmatically button by using xml button

i have 4 button create in programmatically button in for loop, is it possible to disable the onclicklistener function or ontouchlistener function by using button create in xml ? Sorry for my einglish, wish can be understand my question.
Sample Image
Code
public class Tab1 extends Fragment {
TextView textView, test1;
Button button, button2;
LinearLayout rl;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View h = inflater.inflate(R.layout.tab1, container, false);
//Returning the layout file after inflating
//Change R.layout.tab1 in you classest
textView = (TextView) h.findViewById(R.id.textView);
test1 = (TextView) h.findViewById(R.id.test1);
button = (Button) h.findViewById(R.id.button);
button2 = (Button) h.findViewById(R.id.button2);
rl = (LinearLayout) h.findViewById(R.id.tlayout);
for (int i = 1; i < 5; i++) {
final Button btnAddARoom = new Button(getActivity());
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
rl.addView(btnAddARoom);
btnAddARoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
test1.setText("qweqweqweqwe");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAddARoom.setOnClickListener(null);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
test1.setText("111111111111111");
}
});
}
return h;
}
}
Add all the buttons you created from the for loop into an array.
ArrayList<Buttons> buttons = new ArrayList<Buttons>();
for(int i =1 ; i<5 ; i++) {
final Button btnAddARoom = new Button(getActivity());
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams
(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
rl.addView(btnAddARoom);
buttons.add(YourDynamicallyCreatedButton)
}
Now in your onClick of xml button:
onClick(){
for(Button button: buttons){
button.setEnable(false)
}
}
Note:
When we add a view(button or text..) via xml we give it an id. We can access these elements with this ID. Similarly, when we create buttons dynamically, we need to set id to the buttons/views.
Call setEnable(false) on your Button reference
Example:
Button b ;
..
..
b.setEnable(false);
Keep reference of your programatically added buttons:
Button[] buttons = new Buttons[5];
for(int i =0 ; i<buttons.length ; i++) {
buttons[i] = new Button(getActivity());
final Button btnAddARoom = buttons[i];
RelativeLayout.LayoutParams params;
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
btnAddARoom.setText("Add");
btnAddARoom.setLayoutParams(params);
rl.addView(btnAddARoom);
btnAddARoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
test1.setText("qweqweqweqwe");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAddARoom.setOnClickListener(null);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
test1.setText("111111111111111");
}
});
}
Now when you want to disable these buttons:
private disableButtons() {
for(int i=0;i<buttons.length;i++) {
buttons[i].setEnabled(false);
}
}
Hope it will help you!
If you have a dedicated parent for the four buttons then you can eliminate the Arralist or array.
LinearLayout ll = ..//your linear layout or any other parent
final int childcount = ll.getChildCount();
for (int i = 0; i < childcount; i++) {
View view = ll.getChildAt(i);
if (view instanceof Button) {
view.setEnabled(false);
}
}

Can a TextView inside LinearLayout container be collapsed and expand on Button click?

I can dynamically add the text fields in my LinearLayout container.
Now I need to collapse those added fields in click of the Button those added fields should get collapse with any label.
Can it be done? Below is the code that i can add the EditText dynamically.
txtHeading = (EditText)findViewById(R.id.heading);
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
buttonAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0)
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.list_view, null);
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.layout_icon_select);
TextView textOut = (TextView)addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
textIn.setText(null);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}
});
container.addView(addView);
}}});
btnsave = (Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to insert here?
on click to save button in need to collapse all the textView Elements.
let us consider Heading is the label and it is named as Gender so if i added the options as male and female then after clicking the save button this should get collapsed under the Heading.
Based on what I'm kind of guessing that you want... I would create a custom view class based on a linear layout. Each having two edit texts.
Create and add this class to dynamically when the add button is pressed. When the save button is pressed, you can loop over the parent LinearLayout's children and then call a helper method to collapse the second edit text element.
To Loop over the parent and collapse children. Now the CustomElement and the collapseOptionField() call is custom code you must write.
LinearLayout parentLayout = findViewById(...);
for ( int i = 0; i < parentLayout.getChildCount(); i++ ) {
CustomElement ce = parentLayout.getChildAt(i);
ce.collapseOption();
}
Update
Custom class with collapse-able option:
public class TextWithOption extends LinearLayout {
EditText edit0;
EditText edit1;
public TextWithOption(Context context, AttributeSet attrs) {
this(context);
}
public TextWithOption(Context context) {
super(context);
View view = LayoutInflater.from(context).inflate(R.layout.edit_text_option, null);
edit0 = (EditText) view.findViewById(R.id.edit_text0);
edit1 = (EditText) view.findViewById(R.id.edit_text1);
addView(view);
}
public void collapseOption() {
edit1.setVisibility(View.GONE);
}
public void showOption() {
edit1.setVisibility(View.VISIBLE);
}
}
Activity code that will add new options and then collapse them:
final LinearLayout optionsLayout = (LinearLayout) findViewById(R.id.outer_layout);
Button addButton = (Button) findViewById(R.id.button_add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextWithOption to = new TextWithOption(context);
optionsLayout.addView(to);
}
});
((Button) findViewById(R.id.button_save)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for ( int i = 0; i < optionsLayout.getChildCount(); i++ ) {
((TextWithOption)optionsLayout.getChildAt(i)).collapseOption();
}
}
});
public static void collapse(final View v) {
ScaleAnimation anim = new ScaleAnimation(1, 1, 1, 0);
v.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
v.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
onclick of button write view.collapse
view equals to whatever view you want collapse

When inflating a layout xml dynamically multiple times, how can I differentiate or identify the Button widgets?

I am inflating an xml having button, multiple times and i am able to do so perfectly but the problem is when I click the button,i want to show which button is clicked.
public class InflateExActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
Button b;
LinearLayout lLayout;
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i = 0; i < 3; i++) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
t = (TextView) inflater.inflate(R.layout.texts, null);
b.setTag(i); // you'll get 0,1,2 as
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(this);
}
}
public void onClick(View v) {
}
}
You can use setTag() to each button. Inside the for loop you can assign button.setTag(). And you can use getTag() to retrieve button's tag. After you inflate the layout, add a tag to your button
EDIT2:
You should inflate the layout and then look up for your button id. See below:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
final Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.buttons, null);
b = v.findViewById(R.id.your_button_id);
// b = (Button) inflater.inflate(R.layout.buttons, null);
b.setTag(i); // you'll get 0,1,2 as tags
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int specificButton = (Integer)v.getTag();//Changed here.......
Toast.makeText(InflateExActivity.this, "Button Clicked"+Integer.toString(specificButton),
Toast.LENGTH_LONG).show();
}
});
}
}
}
items you are adding programmatically, you must have to assign ids to them.
b.setId(1);
EDITED:
public class DynamicLayoutActivity extends Activity implements OnClickListener{
private static final int MY_BUTTON = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
// add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
}
public void onClick(View v) {
Toast toast;
Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
switch (v.getId()) {
case MY_BUTTON:
toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
}
LATEST:
public class InflateExActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lLayout;
Button b = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int i=0;i<3;i++){
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
b = (Button) inflater.inflate(R.layout.buttons, null);
b.setId(i);
lLayout = (LinearLayout) findViewById(R.id.layout1);
lLayout.addView(b);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(InflateExActivity.this, "Button Clicked :"+v.getId(),
Toast.LENGTH_LONG).show();
}
});
}
}
Use the view tag
View.setTag(Object tag);
You can set a string or a complex object like a class to the tag.

Categories

Resources