How can I create a TextView programmatically in a Linear Layout? - java

I'm trying to make a TextView programmatically in a LinearLayout. The program includes a checking system to check if its been added already and the prompt for creating the textview is an option in a spinner. Here is the full onClick method for the spinner
public void onClick(String Ingredient, int i) {
Toast.makeText(Kitchen.super.getContext(), "Selected "+Ingredient, Toast.LENGTH_SHORT).show();
if(Ingredient.equals(tomatoSauce.name)) {
if (tomatoSauce.init == 0){
tomatoSauce.init = 1;
TextView one = new TextView(getContext());
one.setText(Ingredient);
mainll.addView(one);
}
} else if(Ingredient.equals(chicken.name)) {
chicken.init = 1;
} else if(Ingredient.equals(olives.name)){
olives.init = 1;
}
}
The Linear layout is identified from the xml layout when the app is started in a separate method.
final LinearLayout mainll = (LinearLayout) getActivity().findViewById(R.id.main);
The app crashes upon selecting Tomato Sauce from the menu despite the lack of identified coding errors. Any help with this issue would be greatly appreciated.

Try to add below lines of code:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout_id);
TextView tv = new TextView(this);
tv.setText("hallo hallo");
tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
linearLayout.addView(tv);

Related

Is it possible to set color and size attributes of programmatically created radio buttons?

In an activity java file, we created radio buttons dynamically in a for loop to display when the activity is run. However, because they are dynamically created, we are am unable to edit their properties (such as color, text size, etc) as in a typical xml file. How can we set such properties (color, size, etc...) programmatically?
public void PrintGames(ArrayList<String> games,String league ) {
setContentView(R.layout.activity_api_connection_test);
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
RadioGroup rg2 = new RadioGroup(this);
rg2.setOrientation(LinearLayout.VERTICAL);
//ArrayList<RadioButton> buttons = new ArrayList<RadioButton>();
for (int i = 0; i < games.size(); i++) {
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(LinearLayout.VERTICAL);
RadioButton button = new RadioButton(this);
RadioButton button2 = new RadioButton(this);
button.setText("Home");
button2.setText("Away");
button.setId(View.generateViewId());
button2.setId(View.generateViewId());
TextView textbutton = new TextView(this);
rg.addView(textbutton);
rg.addView(button);
rg.addView(button2);
textbutton.setText("" + games.get(i));
rg2.addView(rg);
}
layout.addView(rg2);
if (games.isEmpty()) {
TextView nogames = new TextView(this);
nogames.setText("No Games today");
layout.addView(nogames);
} else {
Button submit = new Button(this);
submit.setText("Submit");
layout.addView(submit);
//on click listner
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Store(rg2,league);
}
});
}
}
I found some threads saying its not possible for radio buttons and there was suggestions to create vector asset drawables, but many of those threads are outdated (2011), and I have a feeling its possible now with the advanced studio we have.

I want to create a checkbox when button is clicked

I want to make it so that every time someone types something in the editText and clicks the button, the text comes up. It does it in my code, but I also want to add a checkbox next to it. How can I add the checkbox every time the button is pressed?
This is how it looks in the emulator right now after I typed test in the editText:
https://gyazo.com/6b9a050976ecd2c4b509220263bbdce1
The second problem is: when I write a second todo, it overwrites the last one so right now I can only have 1 todo. Why?
Code:
final TextView textViewPrint;
Button btn_print;
final EditText editTextType;
textViewPrint = findViewById(R.id.print_text);
btn_print = findViewById(R.id.button_add);
editTextType = findViewById(R.id.test_textEdit);
btn_print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textViewPrint.setText(editTextType.getText().toString()) ;
editTextType.setText("");
}
});
You can add to your layout programmatically after it has been inflated. Add an id to your LinearLayout:
android:id ="#+id/layout"
Then in OnCreate (after your existing code), get a reference to it and add controls as you wish. And add these lines in OnCreate, For example:
LinearLayout l = (LinearLayout)findViewById(R.id.layout);
CheckBox cb = new CheckBox(this);
int lHeight = LinearLayout.LayoutParams.MATCH_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
l.addView(cb, new LinearLayout.LayoutParams(lHeight, lWidth));
setContentView(l);
First You need add to LinearLayout layout
LinearLayout l = (LinearLayout)findViewById(R.id.layout);
btn_print.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = new CheckBox(this);
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cb.setLayoutParams(lparams);
l.addView(cb);
}
});

How to get data from dynamically created EditText and TextView inside a linearlayout?

In my main.xml I have a LinearLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linearMain"
>
</LinearLayout>
Then, inside my Main.java I am retrieving values from the DB (name and price of an item). Then, I dynamically created my form using the below code:
Cursor cursor = mydb.getAllJuice();
lm = (LinearLayout) findViewById(R.id.linearMain);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
while (cursor.moveToNext()) {
int cid = cursor.getInt(0);
String id = Integer.toString(cid);
String name = cursor.getString(1);
String price = cursor.getString(2);
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(name+" ");
ll.addView(product);
// Create TextView
TextView pricetxt = new TextView(this);
pricetxt.setText(" "+price);
ll.addView(pricetxt);
// Create TextView
TextView currency = new TextView(this);
currency.setText(" LL ");
ll.addView(currency);
// Create TextView
TextView qtylabel = new TextView(this);
qtylabel.setText("QTY ");
ll.addView(qtylabel);
EditText qty = new EditText(this);
qty.setMinLines(1);
qty.setMaxLines(3);
ll.addView(qty);
lm.addView(ll);
}
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
final Button btn = new Button(this);
// Give button an ID
int j = 122;
btn.setId(j+1);
btn.setText("Add To Cart");
// set the layoutParams on the button
btn.setLayoutParams(params);
//Add button to LinearLayout
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
The user will be able to enter the number of items and consequently onClick of the button a TextView will be manipulated.
To fill this textview I will need to loop on all the items that were created to check the price and check how the number that the user entered. I tried using the below code, however I am not able to access the specific item that I want as I have in each row 2 TextView and 1 editText:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// code will be here
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
total = 0 ;
View v1 = null;
for(int i=0; i<lm.getChildCount(); i++) {
v1 = lm.getChildAt(i);
}
}
});
How can I access the different element in the v1?
You can use tag parameter of your Views (TextView, EditText etc.): setTag(Object) . Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. Check Android documentation for more details.
P.S. Instead to use your approach, you can use RecyclerView (or older ListView) with ViewHolder. This already mentioned in comments.
Answer to your question:
The problem is that your "product", "pricetxt", "btn" variables are local variables and gets garbage collected after your current loop iteration is over.
Well you can implement view holder pattern in your project.
Create a class named ViewHolder
class ViewHolder{
LinearLayout ll;
TextView product;
TextView pricetxt ;
TextView currency ;
TextView qtylabel ;
EditText qty ;}
public ViewHolder(LinearLayout ll TextView product TextView pricetxt TextView currency TextView qtylabel EditText qty)
{
this.l1= l1;
this.product=product;
this.pricetxt=pricetxt;
this.currency = currency;
this.qtylabel = qtylevel;
this.qty = qty;
}
This class can hold all your data by passing all these parameters (qty, pricetxt, etc).
Now you have to maintain a List for this ViewHolder Object at the top. You can do this as-
List myList<ViewHolder> = new ArrayList<ViewHolder>();
At the end of every iteration, create and add the ViewHolder object;
You can do this as follows
ViewHolder currentView = new ViewHolder(l1.product,pricetxt,currency,qtylabel,qty);
myList.add(currentView);
myList.add(currentView);
You can access any ViewHolder object maintained inside the list at position "index" as
myList.get(index);
Or the EditText "qty" as
myList.get(index).qty;
In this way you can access your created EditTexts and TextView even after the loop iteration is over.
My Suggestion:- No one does it in this way. As suggested some guys over here you should you android implement recommended RecyclerView which is much more efficient than the current implementation. In cases you can even you ListView.

Handling many dynamically created TextView's

I have the following code:
for (int i = 0; i < dataStrings.length; i++) {
TextView tv1 = new TextView(this);
tv1.setTextSize(TEXT_SIZE);
tv1.setTypeface(Typeface.MONOSPACE);
tv1.setText(dataStrings[i]);
dynamicLL.addView(tv1);
}
Basically, i am creating some amount of TextView's dynamically (the amount is unknown). I want each TextView to have its own OnLongClickListener. My question is how do I give each TextView its own unique OnLongClickListener when the TextViews are generated in this way, and how do I handle the clicks once the listener has been created?
You can just set them in your for loop, like this
OnLongClickListener longClickListener = new OnLongClickListener () {
#Override
public void onLongClick (View v) {
switch (v.getId()) ...
}
};
for (int i = 0; i < dataStrings.length; i++) {
TextView tv1 = new TextView(this);
tv1.setId(i * 1000);
tv1.setOnLongClickListener(longClickListener);
}
In your switch in a listener you can then check what TextView was pressed and do according action.

Setting ArrayList entries as ViewFlipper children

There are over 30 views to be displayed in my activity. Each one is a RelativeLayout with nested ImageView and some TextViews within (some of them are static, some of them are variable). Refactored to programmatic way of displaying results it looks like:
tbnImages = db.getTbnImages();
tbnNames = db.getTbnNames();
tbnExts = db.getTbnExts();
tbnDescs = db.getTbnDescs();
vf = (ViewFlipper) findViewById(R.id.viewFlipperTbnImages);
vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in));
vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.left_out));
detector = new SimpleGestureFilter(this, this);
tbnImage = (ImageView) findViewById(R.id.tbnImage);
tbnName = (TextView) findViewById(R.id.tbnName);
tbnExt = (TextView) findViewById(R.id.tbnExt);
tbnDesc = (TextView) findViewById(R.id.tbnDesc);
How should I configure my ViewFlipper so that .showNext() and .showPrevious() methods would display proper views, including correct behaviour when launching method upon the last view (.showNext() redirects to the first view) and the first one (.showPrevious() presents the last view)?
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
vf.showPrevious();
break;
case SimpleGestureFilter.SWIPE_LEFT:
vf.showNext();
break;
}
All variables (ImageView picture and TextView texts) are taken from an ArrayList. How to set them as ViewFlipper children?
You need to generate all the 30 views and add them as children of the ViewFlipper. If all your views share one single layout, you should create a custom view to handle it.
public class CustomView extends RelativeLayout{
public CustomView(Context context, Uri imageUri, String tbnName, String tbnDescripton, String tbnDesc) {
super(context);
LayoutInflater.from(context).inflate(R.layout.your_layout_resource, this, true);
ImageView tbnImage = (ImageView) findViewById(R.id.tbnImage);
TextView tbnName = (TextView) findViewById(R.id.tbnName);
TextView tbnExt = (TextView) findViewById(R.id.tbnExt);
TextView tbnDesc = (TextView) findViewById(R.id.tbnDesc);
tbnImage.setImageURI(imageUri);
tbnName.setText(tbnName);
tbnImage.setText(tbnDescription);
tbnExt.setText(tbnDesc);
}
}
Where 'your_layout_resource' is your current RelativeLayout resource with a 'merge' element as a root. Then you just have to create all the views you need and add them to your ViewFlipper:
for(int i = 0; i<tbnImages.size(); i++){
vf.addView(new CustomView(context,
tbnImages.get(i),
tbnNames.get(i),
tbnDescripton.get(i),
tbnDescs.get(i)));
}
Anyway, 30 views are a lot of views. Are you sure a ViewPager wouldn't work for you?

Categories