Issue
I want to add an "ingredient" EditText view next to a "quantity" EditText view, pressing an "add" Button. Here's the starting layout code:
<LinearLayout android:id="@+id/ingredients_line_layout"
android:layout_below="@+id/title_line_layout"
android:layout_height="wrap_content"
android:layout_margin="@dimen/layout_margin"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<EditText
android:id="@+id/ingredientsField"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:hint="@string/ingredients"
android:inputType="text" />
<EditText
android:hint="@string/quantity"
android:id="@+id/quantityField"
android:inputType="number"
android:layout_height="match_parent"
android:layout_margin="@dimen/boxes_margin"
android:layout_width="wrap_content" />
<com.google.android.material.button.MaterialButton
android:id="@+id/add_ingredient_btn"
android:layout_height="wrap_content"
android:layout_margin="@dimen/boxes_margin"
android:layout_width="wrap_content"
android:text="@string/add"
app:icon="@drawable/ic_add_ingr_btn" />
</LinearLayout>
How can I implement the onClick method for the button, in the corresponding activity?
Solution
- You need to set
OnClickListener
for "add" button; - Create a view you want to add;
- Find
ingredients_line_layout
layout and add your view to it.
See code below:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
View button = findViewById(R.id.add_ingredient_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewGroup layout = (ViewGroup) findViewById(R.id.ingredients_line_layout);
EditText ingredient = new EditText(YourActivity.this);
ingredient.setHint(R.string.ingredients);
layout.addView(ingredient, 1);
}
});
}
Answered By - Andrew Churilo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.