How to get text from TextView inside a CardView? - java

Inside a CardView I have a LinearLayout with three TextViews in it and I want to get the text from these TextViews. My XML-file looks like this:
<LinearLayout
android:id="#+id/defense"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
>
<android.support.v7.widget.CardView
android:id="#+id/cardCB"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1"
app:cardBackgroundColor="#android:color/transparent"
app:cardElevation="0dp">
<LinearLayout
android:id="#+id/innerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Rannochia"
android:textAlignment="center"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="78"
android:textAlignment="center"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CB"
android:textAlignment="center"
android:textStyle="bold"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Then I want to iterate through all CardViews in the parent LinearLayout and get the TextViews. Something like this:
for (int i = 0; i < defense.getChildCount(); i++){
String getName = ((CardView)defense.getChildAt(i)).getText().toString();
id[i] = getName;
}
But I'm not able to call the methods getText().toString(); like this. How can I get the text from these TextViews inside the CardView?

So many options in here.
1. Give id for your TextViews
2. Use for in LinearLayout with id innerLayout
3. When your UI is dynamic and you need to get TextViews from defense
for (int i = 0; i < defense.getChildCount(); i++){
CardView card = defense.getChildAt(i);
ViewGroup viewGroup = ((ViewGroup)card.getChildAt(0));
for(int j=0;j<viewGroup.getChildCount();j++){
String getName = ((TextView)viewGroup.getChildAt(j)).getText().toString();
id[i] = getName;
}
}

Just give the reference to TextView
for (int i = 0; i < defense.getChildCount(); i++){
String getName = ((TextView)defense.getChildAt(i)).getText().toString();
id[i] = getName;
}

It not works because the textview is inside another ViewGroup which is #+id/innerLayout..
i make a simple function for you..
private void loopViews(ViewGroup view) {
for (int i = 0; i < view.getChildCount(); i++) {
View v = view.getChildAt(i);
if (v instanceof EditText) {
// will be executed when its edittext
Log.d("Check", "This is EditText");
} else if (v instanceof TextView) {
// will be executed when its textview,, and get the text..
TextView x = (TextView) v;
String aa = x.getText().toString();
Log.d("Check", "This is TextView with text : " +aa);
} else if (v instanceof ViewGroup) {
// will be executed when its viewgroup,, and loop it for get the child view..
Log.d("Check", "This is ViewGroup");
this.loopViews((ViewGroup) v);
}
}
and you can use it like this..
LinearLayout def = (LinearLayout) findViewById(R.id.defense);
loopViews(def);
hope it can help you.. :)

Related

i want to add two items in this listview from mysql

I am struggling from Listview , how to add two value in this Listview , i am using SimpleAdapter but i can't add two value , Listview shows only one item from database , how to add two values from mysql database . How can i add two values ?
//this is my layout file
//main activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="0dp">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Class :"
android:textSize="17dp"
android:fontFamily="serif"
android:textColor="#000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"/>
<Spinner
android:id="#+id/new_class"
style="#style/Platform.Widget.AppCompat.Spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="#drawable/spinner_background"
android:popupBackground="#fff"
android:fontFamily="serif"
android:layout_marginRight="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:choiceMode="multipleChoice"
android:focusable="false"/>
</LinearLayout>
</LinearLayout>
//this is my row activity file for custom layout
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/thumbImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="sample text"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckedTextView
android:id="#+id/itemCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
</RelativeLayout>
//this is my code
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
sparseBooleanArray = listview.getCheckedItemPositions();
String ValueHolder = "" ;
int i = 0 ;
while (i < sparseBooleanArray.size()) {
if (sparseBooleanArray.valueAt(i)) {
ValueHolder += data4.get(sparseBooleanArray.keyAt(i)) + ",";
}
i++ ;
}
ValueHolder = ValueHolder.replaceAll("(,)*$", "");
Toast.makeText(MainActivity.this, ValueHolder, Toast.LENGTH_LONG).show();
}
});
how to create custom array adapter please help me
just use custom array adapter as shown below
this is my adapter class
public class ItemAdapter extends ArrayAdapter<User> {
// declaring our ArrayList of items
private ArrayList<User> objects;
/* here we must override the constructor for ArrayAdapter
* the only variable we care about now is ArrayList<User> objects,
* because it is the list of objects we want to display.
*/
public ItemAdapter(Context context, int textViewResourceId, ArrayList<User> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(int position, View convertView, ViewGroup parent){
// assign the view we are converting to a local variable
View v = convertView;
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
/*
* Recall that the variable position is sent in as an argument to this method.
* The variable simply refers to the position of the current object in the list. (The ArrayAdapter
* iterates through the list we sent it)
*
* Therefore, i refers to the current User object.
*/
User i = objects.get(position);
if (i != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView btd = (TextView) v.findViewById(R.id.desctext);
// check to see if each individual textview is null.
// if not, assign some text!
if (tt != null){
tt.setText("Name: ");
}
if (ttd != null){
ttd.setText(i.getName());
}
if (mt != null){
mt.setText("Price: ");
}
if (mtd != null){
mtd.setText("$" + i.getPrice());
}
if (bt != null){
bt.setText("Details: ");
}
if (btd != null){
btd.setText(i.getDetails());
}
}
// the view must be returned to our activity
return v;
}
}
set an instance of custom adapter in your list view like this
ItemAdapter itemAdapter = new ItemAdapter(...);
listView.setAdapter(itemAdapter)
if it helped please verify the answer

How to Change Text Color, Size and Font in a Dynamically Created ListView

I am trying to make a to-do list using an EditText and a ListView. How can I change the text font, color and size? I have seen a couple answers using array adapters, but don't know how to apply them to dynamically created ListView items.
Here is what I have so far:
ActivityMain.xml
<RelativeLayout
android:id="#+id/AgendaRL"
android:orientation="vertical"
android:background="#3E2723"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/agenda"
android:layout_width="370sp"
android:layout_height="wrap_content"
android:text="#string/agenda"
android:textSize="40sp"
android:textColor="#b7950b"
android:layout_marginTop="12sp"
android:layout_marginLeft="12sp"
android:layout_marginStart="12sp"
android:layout_marginBottom="0sp" />
<View
android:background="#b7950b"
android:layout_below="#+id/agenda"
android:layout_width="28sp"
android:layout_height="36sp"/>
<EditText
android:id="#+id/aTask"
android:layout_below="#+id/agenda"
android:background="#drawable/ribbon"
android:inputType="text"
android:text="#string/Add_Task"
android:textColor="#3E2723"
android:maxLength="22"
android:maxLines="1"
android:layout_width="330sp"
android:layout_height="36sp"
android:textSize="28sp"
android:layout_marginLeft="28sp"
android:layout_marginStart="28sp"/>
<Button
android:id="#+id/Done"
style="?android:attr/borderlessButtonStyle"
android:layout_marginLeft="250sp"
android:layout_marginStart="250sp"
android:background="#b7950b"
android:text="#string/Done"
android:textColor="#3E2723"
android:textSize="18sp"
android:layout_below="#+id/agenda"
android:layout_width="48sp"
android:layout_height="36sp"
android:onClick="DoneClick"/>
<ListView
android:id="#+id/LVAgenda"
android:layout_below="#+id/aTask"
android:divider="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
MainActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView LVAgenda = (ListView) findViewById(R.id.LVAgenda);
arrayListAgenda = new ArrayList<String>();
arrayAdapterAgenda = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListAgenda);
LVAgenda.setAdapter(arrayAdapterAgenda);
}
public void DoneClick(View v){
EditText aTask = (EditText)findViewById(R.id.aTask);
String agenda = aTask.getText().toString().trim();
if(agenda.isEmpty()){
return;
}
arrayAdapterAgenda.add(agenda);
aTask.setText("Add task");
}
As commonsware said you can use getView() of ArrayAdapter to do this.
I have implemented Facebook friend selector with ListAdapter. I will share the code. May be it helps. Please try.
First make a XML file in layout that defines the layout of each item of your 'to do list'.
In my case it is a facebook profile image and a checked textbox. (There is also a spacer for alignment)
Facebook.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="wrap_content"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingLeft="10dp"/>
<CheckedTextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|right"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:textColor="#android:color/black"
android:textStyle="bold" />
</LinearLayout>
<View
android:id="#+id/spacer"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/white"/>
</LinearLayout>
Now prepare your data array. In my case it is custom class array where each element contains a facebook name, profilepic, and a boolean.
public class Item{
public final String text;
public final Drawable icon;
public boolean isChecked;
public Item(String text, Drawable icon, boolean ischeck) {
this.text = text;
this.icon = icon;
this.isChecked = ischeck;
}
#Override
public String toString() {
return text;
}
}
I call the below code by passing friendsArray from another activity.
final Item[] items = new Item[friendsArray.length];
try {
int a = 1;
for (int i = 0; i < friendsArray.length; i++) {
tsk = new DownloadImageTask();
Bitmap bmp = (Bitmap) tsk.execute(new RaceActivity.FriendInfo[]{friendsArray[i]}).get();
Resources res = getActivity().getResources();
drawable = new BitmapDrawable(res, bmp);
items[i] = new Item(friendsArray[i].name, drawable,false);
}
}
catch(Exception ex)
{
}
Now your data array is prepared. You can pass this to ListAdapter(items in my case).
Its nice to understand the working of a List adapter. I created a scrollable List. What this logic does is it reuses the Views while scrolling.
ListAdapter adapter = new ArrayAdapter<Item>(
getActivity(),
android.R.layout.select_dialog_item,
android.R.id.text1,
items){
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
FaceBookHolder fb = new FaceBookHolder();
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.facebook,null);
fb.Name = (CheckedTextView) v.findViewById(R.id.name);
fb.img = (ImageView) v.findViewById(R.id.img);
fb.spacer = (View) v.findViewById(R.id.spacer);
fb.Name.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
CheckedTextView cv = (CheckedTextView)v;
if(cv.isChecked())
cv.setChecked(false);
else
cv.setChecked(true);
for(int i =0;i< items.length; i++)
{
if(items[i].text == cv.getText())
{
items[i].isChecked = cv.isChecked();
}
}
}
});
v.setTag(fb);
}
else
fb = (FaceBookHolder) v.getTag();
Item itm = items[position];
fb.Name.setText(itm.text);
fb.img.setImageDrawable(itm.icon);
fb.Name.setChecked(itm.isChecked);
return v;
}
};
you get the view in getView(), so you can modify it however you want.(change color , font etc)
Hope it helps! cheers!

how to add rating bar in Linear Layout Dynamically in Android?

I have tried to add rating bar in Linear Layout at dynamically after some textfields. But I'm getting NullPointerException at the line = lL.addView(rating); Can someone help me please how to do this.Thanks in Advance.
Here is my xml file.
<ScrollView
android:id="#+id/scrollField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btnDELETE"
android:layout_below="#+id/textTitle"
android:layout_marginTop="10dp" >
<LinearLayout
android:id="#+id/linearLayoutRatingDetails"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_EmployeeName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="10dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskName"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskDate"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
<TextView
android:id="#+id/tv_TaskRate"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="6dp"
android:text="dfkyjrtl"
android:textColor="#2E1F1F" />
</LinearLayout>
</ScrollView>
Hare is my Activity code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.task_details);
Intent intent = getIntent();
str_IntentName = intent.getExtras().getString("EMP_NAME");
str_IntentTaskName = intent.getExtras().getString("TASK_NAME");
str_IntentDate = intent.getExtras().getString("TASK_DATE");
str_IntentRate = intent.getExtras().getString("TASK_RATE");
numStar = Integer.valueOf(str_IntentRate);
Log.e("integer numStar "," = " + numStar);
lL = (LinearLayout)findViewById(R.id.linearLayoutRatingDetails);
tvEmpName.setText(str_IntentName);
tvTaskName.setText(str_IntentTaskName);
tvDate.setText(str_IntentDate);
tvRate.setText(str_IntentRate);
Create_RatingBar();
}
private void Create_RatingBar()
{
stepSize = (float) 0.5;
rating = new RatingBar(Task_Details.this);
rating.setNumStars(numStar);
rating.setStepSize(stepSize);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
param.topMargin = 500;
rating.setLayoutParams(param);
lL.addView(rating);
}
In order to add it to the LinearLayout from your xml you need to get a "reference" to this LinearLayout in your code. For that you need to ad id it in xml and get an element using this id in your code.
public void onCreate(Bundle savedInstanceState){
//Some other code for other views
ViewGroup container = (ViewGroup) findViewById(R.id.linearLayoutRatingDetails);
setupRatingBar(container)
}
private void setupRatingBar(ViewGroup ratingBarContainer){
RatingBar ratingBar = new RatingBar(Task_Details.this);
//All methods you need to initialize the rating bar
//including setNumStars(), setStepSize() and layout params
ratingBarContainer.addView(ratingBar);
}
Also use more explanatory names. "lL" will cause you headache in the future.

LinearLayout not displaying Items

What i'm trying to do is add create an application that locates some local business. So the activity I'm doing displays the business information. Some business have severals stores located on the city, and some others only have one. So here is my problem: In the View I have Scroll View with all the elements, and a linear layout inside the scrollview. If the business has more then one store, i will add each store information in a new text view and add the text view to the layout (this is done all by code). But at the moment to display the layout, it only displays me one store, instead of showing me 3 or 4. What I'm I doing wrong? Here is the method setupViews(), which is the one in chanrge of the displaying:
private void setupViews() throws SQLException {
ImageView iv = (ImageView) findViewById(R.id.negocio_logo);
try {
iv.setImageBitmap(BitmapFactory.decodeByteArray(toShow.getImgSrc(),
0, toShow.getImgSrc().length));
} catch (NullPointerException npe) {
iv.setBackgroundColor(Color.WHITE);
}
TextView nombreEmpresa = (TextView) findViewById(R.id.nombre_empresa);
nombreEmpresa.setText(toShow.getNombre());
TextView descripcionEmpresa = (TextView) findViewById(R.id.descripcion_empresa);
descripcionEmpresa.setText(toShow.getDescripcion());
TextView direccionEmpresa = (TextView) findViewById(R.id.direccion_empresa);
direccionEmpresa.setText(toShow.getDireccion());
LinearLayout rl = (LinearLayout) findViewById(R.id.linear_layout_si);
TextView suc = (TextView) findViewById(R.id.sucursales_empresa);
sucursalDAO sDAO = new sucursalDAO();
boolean tieneSucursales = sDAO.hasSucursales(toShow.getId());
if (tieneSucursales == false) {
suc.setVisibility(View.GONE);
// sucs.setVisibility(View.GONE);
} else {
suc.setVisibility(View.VISIBLE);
ArrayList<String> sucursales = sDAO.getStringSucursales(toShow
.getId());
ArrayList<TextView> tvs = new ArrayList<TextView>();
for (int i = 0; i < sucursales.size(); i++) {
TextView tv = new TextView(this);
tv.setText(sucursales.get(i));
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tvs.add(tv);
}
for (int i = 0; i < tvs.size(); i++) {
rl.addView(tvs.get(i), i);
}
}
}
And here is the XML of my view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:orientation="vertical" >
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widgetscroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/White"
android:orientation="vertical" >
<ImageView
android:id="#+id/negocio_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:contentDescription="#string/logo_negocio" />
<TextView
android:id="#+id/datos_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/negocio_logo"
android:background="#drawable/barra"
android:text="#string/datos_empresa"
android:textColor="#color/White" />
<TextView
android:id="#+id/nombre_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/datos_empresa"
android:text="#string/testing" />
<TextView
android:id="#+id/descripcion_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nombre_empresa"
android:text="#string/testing" />
<TextView
android:id="#+id/direccion_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/descripcion_empresa"
android:text="#string/testing" />
<TextView
android:id="#+id/sucursales_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/direccion_empresa"
android:background="#drawable/barra"
android:text="#string/sucursales"
android:visibility="gone" />
<LinearLayout
android:id="#+id/linear_layout_si"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/sucursales_empresa" >
</LinearLayout>
<TextView
android:id="#+id/contacto_empresa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/linear_layout_si"
android:text="#string/testing" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I think you forgot to set orientation on LinearLayout and it's showing horitzontal
I bet you forgot to set the orientation of the LinearLayout.

Android Dev: Can't generate multiple layouts dynamically from an XML template

Making a simple program which will generate a multiple choice form. I have an sing_select.xml which acts as the template for making each question. Then, in code I wanted to populate my main.xml with a bunch of these templates customized. Though it works great for the first question, any subsequent questions do not get displayed. Not sure what I'm doing wrong. I know there isn't an overlap as I manually hid the first question.
Java File
public class FormFillerActivity extends Activity
{
private LinearLayout mQuestionList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Must come before setContentView or program crashes
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Must set before accessing layout elements or program crashes
setContentView(R.layout.main);
mQuestionList = (LinearLayout) findViewById(R.id.Body_Layout);
initForm();
}
private void initForm()
{
int count = 1;
ArrayList<String> answers = new ArrayList<String>();
answers.add("Single");
answers.add("Married");
answers.add("Separated");
answers.add("Divorced");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your marital status?", answers));
answers.clear();
answers.add("Male");
answers.add("Female");
mQuestionList.addView(addSingSelectQuestion(count++, "What is your gender?", answers));
}
private View addSingSelectQuestion(int count, String question, ArrayList<String> answers)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View container = inflater.inflate(R.layout.sing_select, null);
((TextView) container.findViewById(R.id.Sing_Select_Num)).setText(count + ") ");
((TextView) container.findViewById(R.id.Sing_Select_Text)).setText(question);
RadioGroup rg = (RadioGroup) container.findViewById(R.id.Sing_Select_Answer);
//Generate radio group answers
Iterator<String> it = answers.iterator();
while (it.hasNext())
{
RadioButton rb = new RadioButton(rg.getContext());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
String ans = it.next();
rb.setId(answers.indexOf(ans));
rb.setLayoutParams(params);
rb.setText(ans);
rb.setTextColor(getResources().getColor(R.color.black));
rb.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_normal));
rg.addView(rb);
}
return container;
}
}
main.xml (stripped out unrelated UI elements)
<?xml version="1.0" encoding="utf-8"?>
...
<ScrollView
android:id="#+id/Body_Scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/Footer"
android:layout_below="#id/Title"
android:scrollbars="vertical" >
<LinearLayout
android:id="#+id/Body_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/marg_normal"
android:padding="#dimen/pad_large" >
</LinearLayout>
</ScrollView>
...
sing_select.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Sing_Select_Layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:padding="8dp" >
<TextView
android:id="#+id/Sing_Select_Num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#) "
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<TextView
android:id="#+id/Sing_Select_Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/Sing_Select_Num"
android:layout_toRightOf="#+id/Sing_Select_Num"
android:text="The Question?"
android:textColor="#color/black"
android:textSize="#dimen/txt_normal" />
<RadioGroup
android:id="#+id/Sing_Select_Answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Sing_Select_Text"
android:layout_below="#+id/Sing_Select_Text"
android:layout_toLeftOf="#+id/Sing_Select_Trans_Button" >
</RadioGroup>
<Button
android:id="#+id/Sing_Select_Trans_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/btn_big"
android:padding="8dp"
android:text="Accept"
android:textSize="#dimen/txt_button" />
</RelativeLayout>
Try to set orientation to vertical for the *Body_Layout* LinearLayout. I think your pushing out of the screen the next rows after the first one(the width for the inflated view is set to fill the parent).

Categories

Resources