Not able to add view dynamically - android

I have linear layout R.id.linearLayoutQuantityPrice in XML.
I want to add a new linear layout inside that dynamically.
The new linear layout has two textviews and one imageview.
List<Price> priceList = database.getItemQuantityPrice(id);
LinearLayout linearLayoutQuantityPrice = (LinearLayout) rowView
.findViewById(R.id.linearLayoutQuantityPrice);
for (int i=0; i<priceList.size() ; i++) {
Price price = new Price();
price = priceList.get(i);
LinearLayout newLinearLayout = new LinearLayout(context);
newLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams newLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLinearLayout.setPadding(2, 2, 2, 2);
newLinearLayout.setWeightSum(3);
int iqpId = price.getIqpId();
String quantityIn = price.getQuantityIn();
int quantity = price.getItmQnt();
int itemPrice = price.getItmPrc();
TextView tvQuantity=new TextView(context);
tvQuantity.setId(price.getIqpId()+10);
tvQuantity.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvQuantity.setTextSize(12);
if(quantityIn.equalsIgnoreCase("gm") && quantity>=1000){
quantity = quantity/1000;
quantityIn = new String("KG");
}
tvQuantity.setText(""+quantity+" "+quantityIn);
newLinearLayout.addView(tvQuantity);
TextView tvPrice=new TextView(context);
tvPrice.setId(price.getIqpId()+11);
tvPrice.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvPrice.setTextSize(12);
tvPrice.setText("Rs. "+itemPrice);
newLinearLayout.addView(tvPrice);
ImageView ivButton = new ImageView(context);
ivButton.setId(iqpId);
ivButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));
ivButton.setImageDrawable(rowView.getResources().getDrawable(R.drawable.add_button));
ivButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int toCartId = v.getId();
Toast.makeText(context, "Added to cart" + toCartId, Toast.LENGTH_SHORT).show();
}
});
linearLayoutQuantityPrice.addView(newLinearLayout);
}
The code doesn't get any errors. But the desired views are not added.

Because you forgot to set the layout params.
newLinearLayout.setLayoutParams(newLayoutParams)

Try to use this. This is worked for me.
ArrayList<Component> components;
LinearLayout llRowContainer;
llRowContainer = (LinearLayout) findViewById(R.id.ll_row_container);
components = IappApp.getContext().getDBManager()
.getComponentList(COMPONENT_TYPE, ACTIVITY_TYPE);
int index = 0;
for (Component component : components) {
View rowView = View.inflate(this, R.layout.dae_general_info_row , null);
llRowContainer.addView(rowView);
final TextView txtViewTitle = (TextView) rowView
.findViewById(R.id.txtViewTitle);
final EditText editTextAns = (EditText) rowView
.findViewById(R.id.editTextAns);
editTextAns.setHint(component.getUnit()+"");
txtViewTitle.setText(++index + ". " + component.getTitle());
editTextAns.setTag(component);
}

Related

Text out of text view

I am currently having a problem with Android application. I am using a table layout with some views in it. The problem is that it seems like the TextView does not wraps the text correctly. However, when I change swipe between fragments it just resizes and it fits as how its supposed to.
This is what is looks like in the first place when the onCreate function is called.
And this is how it looks when I swipe between fragments.
This is the method I used to set up the views inside the table.
private void initializeBookTable(final List<Book> bookList, View view, final Button modifyBtn, final Button deleteBtn)
{
//Get screen width
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
TableLayout table = view.findViewById(R.id.book_tableLayout);
//Border for the text views
final GradientDrawable gd = new GradientDrawable();
gd.setColor(getResources().getColor(R.color.colorTeal));
gd.setCornerRadius(2);
gd.setStroke(2, 0xFF000000);
//Font for the text views
Typeface font = Typeface.create("casual",Typeface.BOLD);
//Header row
TableRow headerRow = new TableRow(this.getContext());
TableLayout.LayoutParams headerRowParams = new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT);
headerRowParams.setMargins(0,1,0,0);
headerRow.setLayoutParams(headerRowParams);
//Header name text view
TextView headerName = new TextView(this.getContext());
headerName.setText(getResources().getString(R.string.book_NAME));
headerName.setBackground(gd);
headerName.setPadding(20,0,20,0);
headerName.setTypeface(font);
headerName.setTextColor(Color.BLACK);
headerName.setMinWidth(screenWidth/4);
headerRow.addView(headerName);
//Header chapter text view
TextView headerChapter = new TextView(this.getContext());
headerChapter.setText(getResources().getString(R.string.book_CHAPTER));
headerChapter.setBackground(gd);
headerChapter.setPadding(20,0,20,0);
headerChapter.setTypeface(font);
headerChapter.setTextColor(Color.BLACK);
headerChapter.setMinWidth(screenWidth/4);
headerRow.addView(headerChapter);
//Header page text view
TextView headerPage = new TextView(this.getContext());
headerPage.setText(getResources().getString(R.string.book_PAGE));
headerPage.setBackground(gd);
headerPage.setPadding(20,0,20,0);
headerPage.setTypeface(font);
headerPage.setTextColor(Color.BLACK);
headerPage.setMinWidth(screenWidth/4);
headerRow.addView(headerPage);
//Header name text view
TextView headerStatus = new TextView(this.getContext());
headerStatus.setText(getResources().getString(R.string.book_STATUS));
headerStatus.setBackground(gd);
headerStatus.setPadding(20,0,20,0);
headerStatus.setTypeface(font);
headerStatus.setTextColor(Color.BLACK);
headerStatus.setMinWidth(screenWidth/4);
headerRow.addView(headerStatus);
//Add row to table
table.addView(headerRow);
for(int i = 0; i < bookList.size(); i++)
{
TableRow row = new TableRow(this.getContext());
//Set text views parameters
TableRow.LayoutParams textViewParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
textViewParams.setMargins(0,1,0,1);
row.setLayoutParams(textViewParams);
//Set text views parameters
TextView name = new TextView(this.getContext());
name.setText(bookList.get(i).getName());
name.setBackground(gd);
name.setPadding(20,0,20,0);
name.setLayoutParams(textViewParams);
TextView chapter = new TextView(this.getContext());
chapter.setText(bookList.get(i).getChapter());
chapter.setBackground(gd);
chapter.setPadding(20,0,20,0);
chapter.setLayoutParams(textViewParams);
TextView page = new TextView(this.getContext());
page.setText(bookList.get(i).getPage());
page.setBackground(gd);
page.setPadding(20,0,20,0);
page.setLayoutParams(textViewParams);
TextView status = new TextView(this.getContext());
status.setText(bookList.get(i).getStatus());
status.setBackground(gd);
status.setPadding(20,0,20,0);
status.setLayoutParams(textViewParams);
//Add text views to the row
row.addView(name);
row.addView(chapter);
row.addView(page);
row.addView(status);
row.setClickable(true);
//Click listener for each row
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TableRow tableRow = (TableRow) view;
selectedRow = tableRow;
//If the row is already selected (in red) deselect it
TextView textViewCheck = (TextView) tableRow.getChildAt(0);
if(selection && textViewCheck.getText().toString().equals(selectedBook.getName()))
{
for(int i = 0; i < 4; i++)
{
TextView textView = (TextView) tableRow.getChildAt(i);
textView.setBackground(gd);
}
//Disable add and modify buttons when row is deselected
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
selection = false;
selectedBook = null;
}
//If the row is not in red check if there is already a selected row
else
{
if(selection)
{
String message = "Please select only one";
Toast.makeText(getContext(), message, LENGTH_SHORT).show();
}
else
{
for(int i = 0; i < 4; i++)
{
TextView textView = (TextView) tableRow.getChildAt(i);
textView.setBackgroundColor(Color.RED);
}
//Enable add and modify buttons when row is selected
modifyBtn.setEnabled(true);
deleteBtn.setEnabled(true);
TextView nameView = (TextView) tableRow.getChildAt(0);
selectedBook = storage.findBook(nameView.getText().toString());
selection = true;
}
}
}
});
//Set row parameters
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0,1,0,1);
row.setLayoutParams(tableRowParams);
table.addView(row);
}
}
This is my onCreate
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.books_fragment,container,false);
storage = InternalStorage.getInstance(this.getContext());
final Button modifyBtn = view.findViewById(R.id.modifyBtn);
final Button deleteBtn = view.findViewById(R.id.deleteBtn);
//Disable modify and delete buttons
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
this.initializeBookTable(storage.getBookList(),view, modifyBtn, deleteBtn);
Button addBtn = view.findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), AddModifyBook.class);
startActivity(intent);
}
});
modifyBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(getActivity(), AddModifyBook.class);
//Passing the selected book to the AddModifyBook activity
intent.putExtra("selectedBook",selectedBook);
startActivity(intent);
selectedBook = null;
selection = false;
}
});
final TableLayout table = view.findViewById(R.id.book_tableLayout);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storage.removeBook(selectedBook);
selectedBook = null;
selection = false;
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
table.removeView(selectedRow);
}
});
return view;
}
And for onResume I have the default.
Another thing that is happening is that if I just set the background of the name (the first column) with the gradient drawable gd then it works but If I set the rest background of the rest of the columns then I have the problem that I have already explained.
So apparently I have managed to solve the issue by using a gradient drawable for the name and a different gradient drawable for the other properties.

How to select one radio button from dynamically created radio buttons?

I have a situation to select one radio button from dynamically created radio buttons. I know it is possible with Radio group but still I am not able to do it because my situation is little different. Let me explain it.
I have a question like "A recent survey found that in British secondary schools" with 4 options like
A.
B.
C.
D.
All data coming from the server in json form. I have created the view dynamically with one question and four options with radio buttons. But what i am understanding is every row is new row and I am not able to select only one radio buttons from all radio buttons. Every button is selecting individually but I want to select only one radio button on which I click.
Any help would be appreciated.
you can see my view below:
My code is :
LinearLayout linearLayoutForQuestions = (LinearLayout) view.findViewById(R.id.questionsLinearLayout);
linearLayoutForQuestions.removeAllViews();
//set the questions for the user
for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {
final List<String> list = new ArrayList();
list.add("SELECT");
TextView textView = new TextView(activity);
textView.setTextSize(15);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setTypeface(typeface1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 20, 0, 0);
textView.setLayoutParams(params);
String question = totalNoOfQuestions.get(ss).getQuestions();
String questionNo = totalNoOfQuestions.get(ss).QuestionNo;
textView.setText("Question " + questionNo + " " + question);
//linearlayout and set data inside it
LinearLayout parent = new LinearLayout(activity);
parent.removeAllViews();
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.VERTICAL);
int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
for (int s = 0; s < optionSize; s++) {
//children of parent linearlayout
LinearLayout layout2 = new LinearLayout(activity);
layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout2.setOrientation(LinearLayout.HORIZONTAL);
layout2.setGravity(Gravity.CENTER);
String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
TextView textView1 = new TextView(activity);
textView1.setText(optionNo);
textView.setTextSize(15);
final RadioButton radioButton = new RadioButton(activity.getApplicationContext());
radioButton.setId(s);
radioButton.setBackgroundResource(R.drawable.settings_background_ripple);
LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
pa.setMargins(10,10,10,10);
radioButton.setLayoutParams(pa);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int checkedRadioButtonId = buttonView.getId();
Toast.makeText(activity, "hit it", Toast.LENGTH_SHORT).show();
}
});
String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
TextView textView2 = new TextView(activity);
textView2.setTextSize(15);
textView2.setText(questionOption);
layout2.addView(textView1);
layout2.addView(radioButton);
layout2.addView(textView2);
parent.addView(layout2);
}
linearLayoutForQuestions.addView(textView);
linearLayoutForQuestions.addView(parent);
}
I have been working on it from a while and finally I find the way how to do it , posting my answer to let others take idea from it. I make it work by taking the array of Textview and Radiogroup outside the inner for loop.
Thank you everyone for the assistance. Happy Coding:)
LinearLayout linearLayoutForQuestions = (LinearLayout) view.findViewById(R.id.questionsLinearLayout);
linearLayoutForQuestions.removeAllViews();
totalNoOfQuestions = readingTests[countReadingTest].getQuestion();
//set the questions for the user
for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {
groupNo = ss;
final List<String> list = new ArrayList();
list.add("SELECT");
TextView textView = new TextView(activity);
textView.setTextSize(15);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setTypeface(typeface1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 20, 0, 0);
textView.setLayoutParams(params);
String question = totalNoOfQuestions.get(ss).getQuestions();
String questionNum = totalNoOfQuestions.get(ss).QuestionNo;
textView.setText("Question " + questionNum + " " + question);
//linearlayout and set data inside it
LinearLayout parent = new LinearLayout(activity);
parent.removeAllViews();
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.VERTICAL);
final int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
final RadioButton[] radioButton = new RadioButton[optionSize];
int size = totalNoOfQuestions.size();
final RadioGroup[] radioGroup = new RadioGroup[size]; //you can also create in xml
radioGroup[ss] = new RadioGroup(activity);
radioGroup[ss].setId(ss + 100);
radioGroup[ss].setOrientation(RadioGroup.VERTICAL)ø;
//this textview is for the optionsNo like A,B,C,D
final TextView[] textView1 = new TextView[optionSize];
LinearLayout layoutOptionsNo = new LinearLayout(activity);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutOptionsNo.setOrientation(LinearLayout.VERTICAL);
layoutOptionsNo.setWeightSum(optionSize);
layoutOptionsNo.setGravity(Gravity.CENTER);
layoutOptionsNo.setPadding(10, 0, 0, 0);
layoutOptionsNo.setLayoutParams(layoutParams);
LinearLayout layoutOptions = new LinearLayout(activity);
layoutOptions.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
layoutOptions.setOrientation(LinearLayout.HORIZONTAL);
layoutOptions.setWeightSum(4);
layoutOptions.setGravity(Gravity.CENTER);
//inner loop for the options for every single question
for (int s = 0; s < optionSize; s++) {
String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
textView1[s] = new TextView(activity);
textView1[s].setText(optionNo);
textView1[s].setTextSize(15);
textView1[s].setGravity(Gravity.CENTER);
LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
pa.setMargins(10, 10, 10, 10);
pa.weight = 1;
textView1[s].setLayoutParams(pa);
String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
radioButton[s] = new RadioButton(activity);
radioButton[s].setId(s);
radioButton[s].setText(questionOption);
radioButton[s].setTextSize(15);
radioButton[s].setPadding(2, 2, 2, 2);
radioButton[s].setBackgroundResource(R.drawable.settings_background_ripple);
LinearLayout.LayoutParams pa2 = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
pa2.setMargins(10, 10, 10, 10);
pa2.weight = 1;
radioGroup[ss].setLayoutParams(pa2);
radioGroup[ss].addView(radioButton[s]);
layoutOptionsNo.addView(textView1[s]);
}
radioGroup[ss].setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int originalId ;
int id = group.getId();{
originalId = id-100;
}
questionNo = totalNoOfQuestions.get(originalId).getQuestionNo();
optionNo = totalNoOfQuestions.get(0).getOptions().get(checkedId).getQuestionOptionNo();
}
});
layoutOptions.addView(layoutOptionsNo);
layoutOptions.addView(radioGroup[ss]);
parent.addView(layoutOptions);
linearLayoutForQuestions.addView(textView);
linearLayoutForQuestions.addView(parent);
}
boolean showOptionHint = totalNoOfQuestions.get(0).OptionList;
LinearLayout linearLayoutForOptions = (LinearLayout) view.findViewById(R.id.optionsLinearLayout);
linearLayoutForOptions.removeAllViews();
if (showOptionHint == true) {
//dynamic creation of options under the quesiton layout
List<ReadingTest.QuestionBean.OptionsBean> questionOptions = readingTests[countReadingTest].getQuestion().get(0).getOptions();
for (int ss = 0; ss < questionOptions.size(); ss++) {
String options = questionOptions.get(ss).getQuestionOption();
String optionsNo = questionOptions.get(ss).getQuestionOptionNo();
TextView textView = new TextView(activity);
textView.setTextSize(18);
textView.setTypeface(typeface);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setText(optionsNo + ". " + options);
linearLayoutForOptions.addView(textView);
}
}
Use RadioGroup as below:
LinearLayout layout = (LinearLayout) findViewById(R.id.layout); //layout defined in xml main activity layout
RadioGroup radioGroup = new RadioGroup(this); //you can also create in xml
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(radioGroup, p);
/*radio button 1*/
RadioButton radioButtonView1 = new RadioButton(this);
radioButtonView1.setText("RadioButton1");
radioButtonView1.setOnClickListener(this);
radioGroup.addView(radioButtonView1, p);
/*radio button 2*/
RadioButton radioButtonView2 = new RadioButton(this);
radioButtonView2.setText("RadioButton2");
radioButtonView2.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView2, p);
/*radio button 3*/
RadioButton radioButtonView3 = new RadioButton(this);
radioButtonView3.setText("RadioButton3");
radioButtonView3.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView3 , p);
/*radio button 4*/
RadioButton radioButtonView4 = new RadioButton(this);
radioButtonView4 .setText("RadioButton4");
radioButtonView4.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView4 , p);
Here you can select only one option out of multiple
As you required how to select value, then please use following code snippet:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show(); //text related to option selected.
}
}
);
Thanks
Hello #Sandeep Singh Bandral
You have done a great Work, Why you are doing such a heavy work
Just Create a Radio Group Work and assign a Id ,and call setOnCheckedChangeListener
You can see here
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.answer1) {
Toast.makeText(getApplicationContext(), "Answer1",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.answer2) {
Toast.makeText(getApplicationContext(), "Answer2",
Toast.LENGTH_SHORT).show();
}else if(checkedId == R.id.answer3) {
Toast.makeText(getApplicationContext(), "Answer3",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Answer4",
Toast.LENGTH_SHORT).show();
}
}
});
In the place of Toast ,DO YOUR STUFF
Test Case:if you don't know how many radio buttons for each Question, you can see the below code over here
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
for(int i=0; i<radioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
if(btn.getId() == checkedId) {
String text = btn.getText();
// do something with text
return;
}
}
}
});
I know this is rather old, but I just had the same problem. The solution is to change the state of RadioButton after adding it to RadioGroup by addView(). I guess this is also what BAKUS tried to say by his sample code.
copied from here

Approach to get values of a dynamically generated textView

I successfully created a dynamic TextView and a Button now when ever the button was clicked the value of a TextView changes.
But the problem is I have a final "submit button" outside a loop which should get the INDIVIDUAL values of each TextView and I cant think of a way how to do it can someone pls give me an approach for this thanks!. pls be nice..
code
Cursor citem= sdb.rawQuery("SELECT * FROM ITEM INNER JOIN CATEGORY ON item.categoryid = category.id where category.categoryname='"+fcat+"'", null);
ScrollView scrollView= new ScrollView(this);
LinearLayout mainLayout= new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
Button border = new Button(this);
border.setId(Integer.parseInt(cuser.getString(cuser.getColumnIndex("id"))));;
border.setText("ORDER");
while (citem.moveToNext())
{
byte[] blob =citem.getBlob(citem.getColumnIndex("itemimage"));
int id = Integer.parseInt(citem.getString(citem.getColumnIndex("id")));
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setTag(id);
int i;
ImageView iv = new ImageView(this);
iv.setId(id);
iv.setImageBitmap(dh.getPhoto(blob));
final TextView txtquantity = new TextView(this);
txtquantity.setId(id);
txtquantity.setText("0");
txtquantity.setTextSize(20);
final TextView txtprice = new TextView(this);
txtprice.setId(id);
txtprice.setText(citem.getString(citem.getColumnIndex("itemprice")));
txtprice.setTextSize(30);
ImageButton btn1 = new ImageButton(this);
btn1.setId(id);
final int id_ = btn1.getId();
btn1.setImageResource(R.drawable.ic_launcher);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
i=Integer.parseInt((String) txtquantity.getText())+1;
txtquantity.setText(String.valueOf(i));
totalprice.setText(String.valueOf(Integer.parseInt(totalprice.getText().toString())+(Integer.parseInt(txtprice.getText().toString())*1)));
}
});
ImageButton btn2 = new ImageButton(this);
btn2.setId(id);
final int id2_ = btn2.getId();
btn2.setImageResource(R.drawable.ic_launcher);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(Integer.parseInt((String)txtquantity.getText())<=0)
{
}
else
{
int i=0;
i= Integer.parseInt((String) txtquantity.getText())-1;
txtquantity.setText(String.valueOf(i));
totalprice.setText(String.valueOf(Integer.parseInt(totalprice.getText().toString())-(Integer.parseInt(txtprice.getText().toString())*1)));
}
}
});
linearLayout.addView(iv);
linearLayout.addView(txtprice);
linearLayout.addView(btn1);
linearLayout.addView(txtquantity);
linearLayout.addView(btn2);
mainLayout.addView(linearLayout);
}
mainLayout.addView(totalprice);
mainLayout.addView(border);
scrollView.addView(mainLayout);
setContentView(scrollView);
Not quite sure what problem you're having? If it's just reading all the TextViews you created in the loop, then you should just keep a list, and send it off for processing when you submit...
List<TextView> tv_list = new ArrayList<TextView>();
while(...){
//In loop..add your tv's
TextView some_tv = new TextView()
tv_list.add(some_tv);
...
}
//In the submit, send them off for processing...
private void process_tvs(List<TextView> tv_list){
for(TextView tv:tv_list){
//Assuming your tv's have numbers...
int val = Integer.valueOf(tv.getText().toString());
//do something....
}
}

setting onclicklistener to numberpicker dynammicaly added android

I have the following situation:
When the app start i show an prompt dialog in which the user can say how many different tickets they want. If they fill in 3 there comes another dialog where they can fill in an description and a price for the tickets.
That part work, but when I want to add eventlistener to the numberpicker so when they click + or - it calcutlates the right price for te ticket.
Like u can see on the image, there are 5 textviews and 1 number picker that are added dynamically.
I've tried the following but that doesn't work:
for (int i = 0; i < differentTickets; i++){
final int j = i;
NumberPicker np = (NumberPicker) findViewById(j+10);
np.setOnNumberPickerChangedListener(new NumberPicker.OnNumberPickerChangedListener() {
#Override
public void onNumberPickerChanged(NumberPicker mynumberpicker) {
TextView tv = (TextView) findViewById(j+100);
tv.setText("test");
}
});
}
This is the code how I add the views dynamically:
for (int i = 0; i < differentTickets; i++) {
ticket t = new ticket();
t.setOmschrijving(omschrijvingenLijst
.get(i).getText().toString());
t.setPrijs(Double.parseDouble(prijzenLijst
.get(i).getText().toString()));
ticketten.add(t);
LinearLayout llTicketsH = new LinearLayout(
MainActivity.this);
llTicketsH
.setOrientation(LinearLayout.HORIZONTAL);
TextView tvv = new TextView(
MainActivity.this);
tvv.setText(omschrijvingenLijst.get(i)
.getText().toString());
tvv.setTextColor(Color.BLACK);
tvv.setTextSize(
TypedValue.COMPLEX_UNIT_DIP, 30);
tvv.setWidth((int) convertDpToPixel(400,
MainActivity.this));
llTicketsH.addView(tvv);
TextView tvPrijs = new TextView(
MainActivity.this);
tvPrijs.setText(prijzenLijst.get(i)
.getText().toString());
tvPrijs.setTextColor(Color.BLACK);
tvPrijs.setTextSize(
TypedValue.COMPLEX_UNIT_DIP, 30);
tvPrijs.setWidth((int) convertDpToPixel(
100, MainActivity.this));
tvPrijs.setGravity(Gravity.RIGHT);
tvPrijs.setId(i);
llTicketsH.addView(tvPrijs);
TextView tvEuro2 = new TextView(
MainActivity.this);
tvEuro2.setText(" €");
tvEuro2.setTextColor(Color.BLACK);
tvEuro2.setTextSize(
TypedValue.COMPLEX_UNIT_DIP, 30);
tvEuro2.setWidth((int) convertDpToPixel(50,
MainActivity.this));
llTicketsH.addView(tvEuro2);
NumberPicker np = new NumberPicker(
MainActivity.this, null);
np.setId(i+10);
llTicketsH.addView(np);
TextView tvPrijsTot = new TextView(
MainActivity.this);
tvPrijsTot.setText("xxx");
tvPrijsTot.setTextColor(Color.BLACK);
tvPrijsTot.setTextSize(
TypedValue.COMPLEX_UNIT_DIP, 30);
tvPrijsTot.setWidth((int) convertDpToPixel(
100, MainActivity.this));
tvPrijsTot.setGravity(Gravity.RIGHT);
tvPrijsTot.setId(i+100);
llTicketsH.addView(tvPrijsTot);
TextView tvEuro = new TextView(
MainActivity.this);
tvEuro.setText(" €");
tvEuro.setTextColor(Color.BLACK);
tvEuro.setTextSize(
TypedValue.COMPLEX_UNIT_DIP, 30);
LinearLayout.LayoutParams MOs = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
tvEuro.setLayoutParams(MOs);
llTicketsH.addView(tvEuro);
llTickets.addView(llTicketsH);
}
}
});
What you can do is getParent of NumberPicker... Then in that parentView get the textView with childPosition in that View to update as per your requirement...
Like this..
for (int i = 0; i < differentTickets; i++){
final int j = i;
NumberPicker np = (NumberPicker) findViewById(j+10);
np.setOnNumberPickerChangedListener(new NumberPicker.OnNumberPickerChangedListener() {
#Override
public void onNumberPickerChanged(NumberPicker mynumberpicker) {
//TextView tv = (TextView) findViewById(j+100);
LinearLayout parView = (LinearLayout) mynumberpicker.getParent();
TextView tv = parView.getChildAt(5);//your child view at position
tv.setText("test");
}
});
}

How can we create dynamic textview?

how to create the textview in code not in xml file. It is because number of textviews will be changing in my application according to some integer.
This is the code to create TextView Dynamically
LinearLayout layout = (LinearLayout ) findViewById(R.id.llayout);
for (int i = 0; i < 3; i++) {
TextView dynamicTextView = new TextView(this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
dynamicTextView.setText("NewYork");
layout.addView(tstate);
}
Maybe thats what you need:
LinearLayout lin = (LinearLayout) findViewById(R.id.myLinear);
for (int i = 0; i <= 10 ; i++)
{
TextView myText = new TextView(this);
myText.setText("textview# "+ i);
lin.addView(myText);
}
Something like the following should be what you need:
final int N = 10; // total number of textviews to add
final TextView[] myTextViews = new TextView[N]; // create an empty array;
for (int i = 0; i < N; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is TextView #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
myTextViews[i] = rowTextView;
}
private LinearLayout ll;
private TextView tv;
// in oncreate()
onCreate()
{
int WrapWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
int WrapHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
tv = new TextView(this);
ll.addView(tv,WrapWidth,WrapHeight);
}
Code is here
final int c = 12;
final TextView[] mtext = new TextView[c];
for (int i = 0; i < c; i++) {
TextView rowtxt = new TextView(this);
rowtxt.setText("Hello" + i);
myLinearLayout.addView(rowtxt);
myTextViews[i] = rowtxt;
myTextViews[i].setOnClickListener(onclicklistener);//textview click
}
OnClickListeners code is here
OnClickListener onclicklistener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == myTextViews[0]){
//do whatever you want....
}
}
};
Hope it is helpful for you
You use TextView textView = new TextView(CurrentActivity.this);
and then you add setter arguments that come with the TextView class

Categories

Resources