How to add a copy of XML dynamically - java

I am making an Android app, and I want to copy some XML code in a Linear Layout, and re-insert it into the Linear Layout so that there are two of the Relative Layouts in the Linear Layout. I would like to do this dynamically by taking this code below:
<LinearLayout
android:id="#+id/tileContainerME"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/tilesAreHERE"
android:layout_width="207dp"
android:layout_height="151dp" >
<TextView
android:id="#+id/bottom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/top1"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="1"
/>
<TextView
android:id="#+id/left1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="2"
/>
<TextView
android:id="#+id/right1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/left1"
android:layout_alignBottom="#+id/left1"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="3"
/>
<TextView
android:id="#+id/top1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:text="4"
/>
</RelativeLayout>
</LinearLayout>
And then simply turning it into this:
<LinearLayout
android:id="#+id/tileContainerME"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/tilesAreHERE"
android:layout_width="207dp"
android:layout_height="151dp" >
<TextView
android:id="#+id/bottom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/top1"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="1"
/>
<TextView
android:id="#+id/left1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="2"
/>
<TextView
android:id="#+id/right1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/left1"
android:layout_alignBottom="#+id/left1"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="3"
/>
<TextView
android:id="#+id/top1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:text="4"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/tilesAreHERE"
android:layout_width="207dp"
android:layout_height="151dp" >
<TextView
android:id="#+id/bottom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/top1"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="1"
/>
<TextView
android:id="#+id/left1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="2"
/>
<TextView
android:id="#+id/right1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/left1"
android:layout_alignBottom="#+id/left1"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="3"
/>
<TextView
android:id="#+id/top1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:text="4"
/>
</RelativeLayout>
</LinearLayout>
See how there would be TWO RelativeLayout sections... I would like to basically make a copy of one and then add it back in (I don't really know how many times I might have to do this in my program, that's why I am not literally inserting it into the XML, I would like to do it from the Java code).
This is what I have so far, but whenever I run it, the layout is wrong. What might be wrong with my code?
LinearLayout m3 = (LinearLayout)findViewById(R.id.tileContainerME);
RelativeLayout m = (RelativeLayout)findViewById(R.id.tilesAreHERE);
RelativeLayout m2 = new RelativeLayout(this);
m2.setLayoutParams(m.getLayoutParams());
m2.setGravity(m.getGravity());
m2.setLayoutDirection(m.getLayoutDirection());
TextView et1 = (TextView) findViewById(R.id.bottom1);
TextView et2 = (TextView) findViewById(R.id.left1);
TextView et3 = (TextView) findViewById(R.id.right1);
TextView et4 = (TextView) findViewById(R.id.top1);
TextView tv1 = new TextView(et1.getContext());
TextView tv2 = new TextView(et2.getContext());
TextView tv3 = new TextView(et3.getContext());
TextView tv4 = new TextView(et4.getContext());
tv1.setLayoutDirection(et1.getLayoutDirection());
tv2.setLayoutDirection(et2.getLayoutDirection());
tv3.setLayoutDirection(et3.getLayoutDirection());
tv4.setLayoutDirection(et4.getLayoutDirection());
tv1.setGravity(et1.getGravity());
tv2.setGravity(et2.getGravity());
tv3.setGravity(et3.getGravity());
tv4.setGravity(et4.getGravity());
tv1.setText(et1.getText());
tv2.setText(et2.getText());
tv3.setText(et3.getText());
tv4.setText(et4.getText());
m2.addView(tv4,et4.getLayoutParams());
m2.addView(tv3,et3.getLayoutParams());
m2.addView(tv2,et2.getLayoutParams());
m2.addView(tv1,et1.getLayoutParams());
m3.addView(m2);
I don't see what's wrong with my code, any suggestions.....
THIS IS THE FULL XML DATA FILE:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<HorizontalScrollView
android:id="#+id/scrollHORIZON"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/linearLayout1" >
<LinearLayout
android:id="#+id/tileContainerME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/tilesAreHERE"
android:layout_width="207dp"
android:layout_height="151dp" >
<TextView
android:id="#+id/bottom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/top1"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="1"
/>
<TextView
android:id="#+id/left1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="2"
/>
<TextView
android:id="#+id/right1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/left1"
android:layout_alignBottom="#+id/left1"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:text="3"
/>
<TextView
android:id="#+id/top1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:text="4"
/>
</RelativeLayout>
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>

Inflating the same layout inside it once again might help you achieve this.
Try this code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
LinearLayout main_layout = (LinearLayout)findViewById(R.id.tileContainerME);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout child = (LinearLayout) inflater.inflate(R.layout.main_layout, null);
main_layout.addView(child, 1);
}
You'll get something like this:

You are probably getting an error message that the View you are trying to add already has a parent. You would need to call removeView() on the parent of your TextViews or removeAllViews() to just remove them all before adding them to your new RelativeLayout. Something like
m.removeAllViews();
m2.addView(et1);
m2.addView(et2);
m2.addView(et3);
m2.addView(et4);
However, if you are adding them multiple times then you probably want to create new instances of them as you do with your RelativeLayout (m2). Then you can use the params that your original TextViews have. If this isn't your current error then please post your logcat but this will cause an exception.
Edit
TextView et1 = (TextView) findViewById(R.id.top1);
TextView et2 = (TextView) findViewById(R.id.right1);
TextView et3 = (TextView) findViewById(R.id.left1);
TextView et4 = (TextView) findViewById(R.id.bottom1);
//Create the new TextViews
TextView tv1 = new TextView(m.getContext()); //if inside Activity you can use this instead of m.getContext()
// set params which you can get from the above TextViews
m2.addView(tv1);
...

I figured it out!
LinearLayout m3 = (LinearLayout)findViewById(R.id.tileContainerME);
RelativeLayout m = (RelativeLayout)findViewById(R.id.tilesAreHERE);
RelativeLayout m2 = new RelativeLayout(m.getContext());
m2.setLayoutParams(m.getLayoutParams());
TextView et1 = (TextView) findViewById(R.id.top1);
TextView et2 = (TextView) findViewById(R.id.right1);
TextView et3 = (TextView) findViewById(R.id.left1);
TextView et4 = (TextView) findViewById(R.id.bottom1);
TextView tv1 = new TextView(et1.getContext());
TextView tv2 = new TextView(et2.getContext());
TextView tv3 = new TextView(et3.getContext());
TextView tv4 = new TextView(et4.getContext());
tv1.setText(et1.getText());
tv2.setText(et2.getText());
tv3.setText(et3.getText());
tv4.setText(et4.getText());
tv1.setLayoutParams(et1.getLayoutParams());
tv2.setLayoutParams(et2.getLayoutParams());
tv3.setLayoutParams(et3.getLayoutParams());
tv4.setLayoutParams(et4.getLayoutParams());
m2.addView(tv1);
m2.addView(tv2);
m2.addView(tv3);
m2.addView(tv4);
m3.addView(m2);
This will make a copy of the previous layout and then add it back into the current layout!

I FOR SURE got it working this time! I used this code:
LinearLayout item = (LinearLayout)findViewById(R.id.tileContainerME);
View child = getLayoutInflater().inflate(R.layout.activity_main, null);
item.addView(child);
It would copy the 'activity_main' class which holds solely the XML data for the tile. Then it copies it into the Horizontal Scroll View! Here is a screenshot of my solution:
http://i.stack.imgur.com/WxoJG.png

Related

Why do i always see the last id in View.OnClickListener?

Why do I always see the last id no matter which text I click?
I would like to see the right fragment displayed in the layout that i created according to the relevant text clicked. I always see the 'alternatives' fragment.
I understood that tags could be helped, but I could not figure out how to use them.
In addition, I tried to use diffrent versions of FragmentManager and FragmentTransaction and even to remove the switch and call each setOnClickListener of textview separately but nothing helped.
This is my Activity file:
IngredientsFragment ingredientsFragment;
FavouritesFragment favouritesFragment;
FeedbacksFragment feedbacksFragment;
Write_Feedback_Fragment writeFeedbackFragment;
AlternativesFragment alternativesFragment;
TextView ingredients;
TextView favourites;
TextView feedbacks;
TextView alternatives;
TextView writeFeedback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
window=this.getWindow();
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
ingredients= (TextView) findViewById(R.id.ingredients_option);
favourites= (TextView) findViewById(R.id.favorites_option);
feedbacks= (TextView) findViewById(R.id.watch_feedback_option);
writeFeedback= (TextView) findViewById(R.id.add_feedback_option);
alternatives= (TextView) findViewById(R.id.alternatives_option);
ingredients.setOnClickListener(this);
favourites.setOnClickListener(this);
feedbacks.setOnClickListener(this);
writeFeedback.setOnClickListener(this);
alternatives.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ingredients_option:
ingredientsFragment= new IngredientsFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,ingredientsFragment).commit();
break;
case R.id.favorites_option:
favouritesFragment= new FavouritesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,favouritesFragment).commit();
break;
case R.id.watch_feedback_option:
feedbacksFragment= new FeedbacksFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,feedbacksFragment).commit();
break;
case R.id.add_feedback_option:
writeFeedbackFragment= new Write_Feedback_Fragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,writeFeedbackFragment).commit();
break;
case R.id.alternatives_option:
alternativesFragment= new AlternativesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,alternativesFragment).commit();
break;
}
}
}
This is my XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ProductDetails">
<RelativeLayout
android:id="#+id/recommendation_template"
android:layout_width="match_parent"
android:layout_height="142dp"
android:background="#android:color/white">
<ImageView
android:id="#+id/registartion_arrow"
android:layout_width="45dp"
android:layout_height="34dp"
android:layout_alignParentRight="true"
android:src="#drawable/ic_arrow_forward_black_24dp" />
<TextView
android:id="#+id/rec_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="10dp"
android:text="Recommendation:"
android:textSize="25dp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<ImageView
android:id="#+id/vi_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rec_tv"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_marginTop="26dp"
android:paddingLeft="80dp"
android:src="#drawable/ic_check" />
<TextView
android:id="#+id/vi_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/vi_image"
android:layout_marginLeft="4dp"
android:layout_marginTop="-29dp"
android:layout_toRightOf="#id/vi_image"
android:text="This is for you"
android:textColor="#android:color/black"
android:textSize="20dp" />
<ImageView
android:id="#+id/not_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/vi_image"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_marginTop="3dp"
android:paddingLeft="80dp"
android:src="#drawable/ic_do_not" />
<TextView
android:id="#+id/not_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/not_image"
android:layout_marginLeft="5dp"
android:layout_marginTop="-27dp"
android:layout_toRightOf="#id/not_image"
android:text="Not for you"
android:textColor="#android:color/black"
android:textSize="20dp" />
</RelativeLayout>
<HorizontalScrollView
android:id="#+id/recommendation_scrollView"
android:layout_width="match_parent"
android:layout_height="83dp"
android:layout_below="#id/recommendation_template"
android:layout_marginTop="7dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/recommendation_template"
style="?android:attr/borderlessButtonStyle">
<TextView
android:id="#+id/ingredients_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:drawableTop="#drawable/ingredients"
android:text="Ingredients" />
<TextView
android:id="#+id/favorites_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:drawableTop="#drawable/ic_star"
android:paddingLeft="80dp"
android:text="Favorites" />
<TextView
android:id="#+id/watch_feedback_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:drawableTop="#drawable/customer_review"
android:paddingLeft="145dp"
android:text="Feedbacks" />
<TextView
android:id="#+id/add_feedback_option"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:drawableTop="#drawable/write_feedback"
android:paddingLeft="220dp"
android:text="Write feedback" />
<TextView
android:id="#+id/alternatives_option"
android:layout_width="408dp"
android:layout_height="90dp"
android:layout_gravity="left"
android:drawableTop="#drawable/ic_alternatives"
android:paddingLeft="320dp"
android:text="Alternatives" />
</FrameLayout>
</HorizontalScrollView>
<ScrollView
android:id="#+id/scrollView_container"
android:layout_width="match_parent"
android:layout_height="499dp"
android:layout_below="#id/recommendation_scrollView">
<RelativeLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="463dp">
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Your code should work like that. The problem is your layout. See the textviews in your FrameLayout. Your defining a paddingLeft and layout_width so, that your textview alternatives_option is overlaying all the other textviews. Thats why in the onclick you always get the id of that view.
I suggest doing a tutorial about XML layout.
<TextView
android:id="#+id/alternatives_option"
android:layout_width="408dp"
android:layout_height="90dp"
android:layout_gravity="left"
android:drawableTop="#drawable/ic_alternatives"
android:paddingLeft="320dp"
android:text="Alternatives" />

Rating bar shows more stars when I rotate my application

I have this weird issue with my rating bar stars.
This is my app in vertical position
This is my app in horizontal position
As you can see the stars completely change
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/main"
tools:context="com.example.draganam.blankapp.Nivo1Activity">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:shrinkColumns="1,0" android:stretchColumns="0,1">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="50dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/slika0"
android:src="#drawable/becutan1"
android:layout_column="0"
android:layout_marginRight="40px" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/slika1"
android:src="#drawable/blizoo1"
android:layout_column="1" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<RatingBar
android:id="#+id/rb0"
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0"
android:isIndicator="true"
android:scaleX="0.7"
android:scaleY="0.7"/>
<RatingBar
android:id="#+id/rb1"
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0"
android:isIndicator="true"
android:scaleX="0.7"
android:scaleY="0.7"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="50dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/slika2"
android:src="#drawable/brilijant1"
android:layout_column="0"
android:layout_marginRight="40px" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/slika3"
android:src="#drawable/vitaminka1"
android:layout_column="1" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<RatingBar
android:id="#+id/rb2"
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0"
android:isIndicator="true"
android:scaleX="0.7"
android:scaleY="0.7"/>
<RatingBar
android:id="#+id/rb3"
style="?android:attr/ratingBarStyleIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0"
android:isIndicator="true"
android:scaleX="0.7"
android:scaleY="0.7"/>
</TableRow>
</TableLayout>
</RelativeLayout>
This is my java code:
Context ctx2 = this;
String[][] arrayWithInformations = new String[5][];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nivo1);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
DatabaseOperations databaseOperations = new DatabaseOperations(ctx2);
Cursor cursorLogo = databaseOperations.getInformationsForLogos(databaseOperations);
// looping through all rows and adding to list
Integer i = 0;
if (cursorLogo.moveToFirst()) {
do {
String[] helperArray = {cursorLogo.getString(0),cursorLogo.getString(1),cursorLogo.getString(2),cursorLogo.getString(3),
cursorLogo.getString(4),cursorLogo.getString(5)};
arrayWithInformations[i] = helperArray;
i++;
} while (cursorLogo.moveToNext());
}
int firstRating = Integer.parseInt(arrayWithInformations[0][4]);
int secondRating = Integer.parseInt(arrayWithInformations[1][4]);
int thirdRating = Integer.parseInt(arrayWithInformations[2][4]);
int fourthRating = Integer.parseInt(arrayWithInformations[3][4]);
RatingBar rb0 = (RatingBar) findViewById(R.id.rb0);
rb0.setRating(firstRating);
RatingBar rb1 = (RatingBar) findViewById(R.id.rb1);
rb1.setRating(secondRating);
RatingBar rb2 = (RatingBar) findViewById(R.id.rb2);
rb2.setRating(thirdRating);
RatingBar rb3 = (RatingBar) findViewById(R.id.rb3);
rb3.setRating(fourthRating);
I get the rating values from database file and everything works fine , the stars are ok but when I rotate the phone they are all wrong. I know that when u rotate your phone the current activity gets loaded again, but it's the same code and it loads wrong. Maybe it's multiplying the stars.. I may sound funny but I have no idea what is going wrong. Someone please give me a lead..
I found out the problem !
android:shrinkColumns="1,0" android:stretchColumns="0,1"
Setting this to the TableLayout caused this strange issue.
Thanks everyone for your interest in helping me ..

Error when generating dynamic content

I'm trying to generate form elements from a template when the user clicks on a button. I created the template and the container layout for the new forms with XML. Its successfully generating the first form where I'm telling it to generate, but when I try to generate more forms beyond the first one its giving me an error: "the specified child already has a parent. You must call removeView() on the child's first parent". Any clue as to what I should do so as to generate more than one element? I've tried changing the id of the newly created forms but that's giving me a null pointer exception and crashing. Thank you.
public class MakeQuestion extends Activity implements OnClickListener{
private static final int MY_BUTTON = 9000;
int templateID = 1;
Button b;
Button target;
View insertPoint;
Button testTemplate;
View v1;
RelativeLayout.LayoutParams templateParams;
LayoutInflater vi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.make_question);
Initialize();
}
public void Initialize(){
//button for adding new forms
b = (Button) findViewById(R.id.makeLayoutButton);
b.setOnClickListener(this);
//get the template form to be duplicated
vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v1 = vi.inflate(R.layout.form_template, null);
//set the params for the element that will have dynamically generated content below it
templateParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//container where forms will be contained in
insertPoint = findViewById(R.id.questionsContainer);
//view where new form will go below
View belowContainer = findViewById(R.id.questionTemplateFake);
//set id for layout params of view
belowContainer.setId(1);
//set rule for new forms to go below view 'belowContainer'
templateParams.addRule(RelativeLayout.BELOW, belowContainer.getId());
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.makeLayoutButton:
v1 = vi.inflate(R.layout.form_template, null);
//add view to the insertPoint
((LinearLayout) insertPoint).addView(v1);
break;
}
}
}
Added forms should go in "questionsContainer" which is set to be below "questionTemplateFake"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grey_background" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#8B459A"
android:baselineAligned="false"
android:clipToPadding="false" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/logo_small" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:src="#drawable/settings" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:src="#drawable/search" />
</RelativeLayout>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/relativeLayout1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relative12"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="WHAT IS YOUR QUESTION?" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/save_button"
android:layout_alignBottom="#+id/save_button"
android:layout_alignRight="#+id/textView1"
android:text="ADD PICTURE OR VIDEO"
android:textSize="10sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="14dp"
android:background="#drawable/textlines"
android:ems="10"
android:hint="50 WORDS OR LESS"
android:inputType="textMultiLine"
android:paddingLeft="5dp" />
<Button
android:id="#+id/save_button"
android:layout_width="75dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/editText1"
android:layout_marginTop="16dp"
android:background="#drawable/purplebutton"
android:text="BROWSE"
android:textColor="#drawable/button_text_color"
android:textSize="10sp" />
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/save_button"
android:layout_marginTop="25dp"
android:text="CREATE AN ANSWER" />
<RelativeLayout
android:id="#+id/questionTemplateFake"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/TextView01" >
<Button
android:id="#+id/Button02eew"
android:layout_width="75dp"
android:layout_height="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/purplebutton"
android:text="BROWSE"
android:textColor="#drawable/button_text_color"
android:textSize="10sp" />
<EditText
android:id="#+id/EditText02"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_above="#+id/Button02"
android:layout_alignParentLeft="true"
android:background="#drawable/textlines"
android:ems="10"
android:hint="50 WORDS OR LESS"
android:inputType="textMultiLine"
android:paddingLeft="5dp" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginRight="19dp"
android:layout_toLeftOf="#+id/Button02"
android:text="ADD PICTURE OR VIDEO"
android:textSize="10sp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/questionsContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:layout_below="#+id/questionTemplateFake"
>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/makeLayoutButton"
android:layout_width="100dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_below="#+id/scrollView1"
android:layout_marginRight="17dp"
android:layout_marginTop="79dp"
android:background="#drawable/purplebutton"
android:text="MORE OPTIONS"
android:textColor="#drawable/button_text_color"
android:textSize="10sp" />
</RelativeLayout>
You are trying to add the same instance over and over again. Thus the message that "specific child already exists". You would have to create a new template layout instance with different ID (I suppose) and then try to add it in.
So rather than:
((RelativeLayout) insertPoint).addView(v1, templateParams);
and adding v1 again. Create a new instance
v1 = vi.inflate(R.layout.form_template, null);
set the id for good measures and then add it again in view.
I suppose you don't need to set the id, but you can read more about how id's work here

ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout

I have some problems with this code.
I'm trying to create a dynamically list of news with this format:
|image| - title
|image|- subtitle
this is my little cicle code (a example with random data)
void setListNews(List<Map<String,String>>l){
listaNewsPagina = l;
final Iterator ite = listaNewsPagina.iterator();
LinearLayout lin = (LinearLayout)findViewById(R.id.linear_sezione_news);
LinearLayout lineare = (LinearLayout)findViewById(R.id.lineare);
while(ite.hasNext()){
Map<String,String> map = (Map<String, String>) ite.next();
ImageView imm = (ImageView)findViewById(R.id.immagine);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.relative);
TextView titolo = (TextView)findViewById(R.id.titolo);
TextView sottoTitolo = (TextView)findViewById(R.id.sottoTitolo);
titolo.setText("titolooooo");
sottoTitolo.setText("sottoTitoloooooooooooo");
rl.addView(titolo);
rl.addView(sottoTitolo);
lineare.addView(imm);
lineare.addView(rl);
}
lin.addView(lineare);
setContentView(lin);
and this is my layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linear_sezione_news"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background_homepage" >
<LinearLayout
android:id="#+id/lineare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#aadd99"
>
<ImageView
android:id="#+id/immagine"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_marginTop="4dp"
android:src="#drawable/ic_launcher" />
<RelativeLayout
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_marginTop="4dp"
android:background="#abfc99">
<TextView
android:id="#+id/titolo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp" />
<TextView
android:id="#+id/sottoTitolo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/titolo"
android:textSize="13dp" />
</RelativeLayout>
</LinearLayout>
<ListView
android:id="#+id/listViewNews"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/ImageButtonPrecc"
android:layout_alignParentLeft="true"
android:layout_below="#+id/lineare"
android:alpha="0.8"
android:background="#aadd99"
android:clickable="true"
android:padding="10dp"
android:textAlignment="center" >
</ListView>
<ImageButton
android:id="#+id/ImageButtonPrecc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_alignParentLeft="true"
android:src="#drawable/bottone_prev"
android:text="#string/load_news" />
<ImageButton
android:id="#+id/ImageButtonSucc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/bottone_next"
android:text="#string/load_news" />
</RelativeLayout>
when I launch the activity with this code I have this problem:
05-19 09:12:45.780: E/AndroidRuntime(21729): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout
I'm trying to create a layout with only Java code...but nothing XD
where I'm wrong?
Change
LinearLayout lin = (LinearLayout)findViewById(R.id.linear_sezione_news);
to
RelativeLayout lin = (RelativeLayout)findViewById(R.id.linear_sezione_news);
The id linear_sezione_news is assigned to a RelativeLayout so you can't cast it to LinearLayout

Inflated items are gone when device orientation changes

Hi i'm using eclipse for deveoping this android app. I'm inflating a layout using inflator and everything works fine.. I'm adding those inflated items one by one to another layout, so when the device's orientation is changed, all those inflated items are gone. The application seems like it has been restarted. But some values are still remaining.. Please help..
public void addNewItem() {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item = li.inflate(R.layout.activity_order_items, null);
orderItemFrameView.add(item);
itemsLayout.addView(item);
setAdditionalFonts(item);
}
private void setAdditionalFonts(View view) {
TextView lblNameTak = (TextView)view.findViewById(R.id.tak_itemNo);
AutoCompleteTextView txtNameTak = (AutoCompleteTextView)view.findViewById(R.id.tak_itemName);
ImageView barScan = (ImageView)view.findViewById(R.id.barcode_scan);
TextView lblRate = (TextView)view.findViewById(R.id.tak_lblRate);
TextView lblQty = (TextView)view.findViewById(R.id.tak_lblQty);
TextView lblTotal = (TextView)view.findViewById(R.id.tak_lblTotal);
TextView rate = (TextView)view.findViewById(R.id.tak_Rate);
EditText2 qty = (EditText2)view.findViewById(R.id.tak_Qty);
TextView total = (TextView)view.findViewById(R.id.tak_Total);
qty.totTextView = total;
qty.rateTextView = rate;
qty.orderTake = this;
qty.index = orderItemFrameView.size() - 1;
qty.sqlDb = SqlDb;
qty.itemName = txtNameTak;
setupBarcodeScan(barScan);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/ubuntu-l.ttf");
Typeface tf2 = Typeface.createFromAsset(getAssets(), "fonts/calibri.ttf");
Typeface tf3 = Typeface.createFromAsset(getAssets(), "fonts/ubu-r.ttf");
Typeface tf4 = Typeface.createFromAsset(getAssets(), "fonts/tahoma.ttf");
lblNameTak.setTypeface(tf3);
txtNameTak.setTypeface(tf2);
lblRate.setTypeface(tf2);
lblQty.setTypeface(tf2);
lblTotal.setTypeface(tf2);
lblNameTak.setText("Item " + (qty.index + 1));
DbAdapterItem dbItem;
TextAdapterItem txtItem;
dbItem = new DbAdapterItem(this, SqlDb);
txtItem = new TextAdapterItem(dbItem, this, qty);
txtNameTak.setAdapter(txtItem);
txtNameTak.setOnItemClickListener(txtItem);
txtNameTak.requestFocus();
}
all these items created by addNewItem() are vanished...
here is the layout from which i'm inflating...
<RelativeLayout 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:paddingBottom ="22dp"
tools:context=".OrderItems" >
<FrameLayout
android:layout_width="match_parent"
android:background= "#888888"
android:layout_height="98dp" >
<TextView
android:id="#+id/tak_itemNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="15dp"
android:layout_marginTop="2.7dp"
android:text="Item 1"
android:layout_gravity="right"
android:textColor="#DDDDDD" />
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="22dp"
android:orientation="vertical"
android:background= "#FFFFFF"
android:layout_height="75dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<AutoCompleteTextView
android:id="#+id/tak_itemName"
android:imeOptions="actionUnspecified"
android:imeActionLabel="search"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="0dp"
android:layout_weight="1.06"
android:completionThreshold="1"
android:ems="10"
android:hint="Item Name / Barcode"
android:inputType="textCapWords"
android:singleLine="true"
android:textColorHint="#DDDDDD" />
<ImageView
android:id="#+id/barcode_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="7dp"
android:paddingRight="7dp"
android:paddingTop="6dp"
android:src="#android:drawable/ic_menu_camera" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<FrameLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
>
<TextView
android:id="#+id/tak_lblRate"
android:layout_width="wrap_content"
android:layout_marginLeft="7dp"
android:layout_height="wrap_content"
android:textColor="#555555"
android:textSize="10sp"
android:text="Rate" />
<TextView
android:id="#+id/tak_Rate"
android:layout_width="match_parent"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="16sp"
android:text="0.00" />
</FrameLayout>
<FrameLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<TextView
android:id="#+id/tak_lblQty"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginRight="7dp"
android:layout_height="wrap_content"
android:textColor="#555555"
android:textSize="10sp"
android:text="Qty" />
<com.sayka.ordergadget.EditText2
android:id="#+id/tak_Qty"
android:layout_width="match_parent"
android:layout_marginBottom="-4dp"
android:layout_marginTop="4dp"
android:inputType="numberDecimal"
android:imeOptions="actionNext"
android:layout_marginLeft="12dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="0.0" />
</FrameLayout>
<FrameLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
>
<TextView
android:id="#+id/tak_lblTotal"
android:layout_width="wrap_content"
android:layout_marginLeft="7dp"
android:layout_gravity="left"
android:layout_height="wrap_content"
android:textColor="#555555"
android:textSize="10sp"
android:text="Total" />
<TextView
android:id="#+id/tak_Total"
android:layout_width="match_parent"
android:layout_gravity="right"
android:layout_marginTop="12dp"
android:layout_marginRight="15dp"
android:layout_height="wrap_content"
android:gravity="right"
android:textSize="16sp"
android:text="0.00" />
</FrameLayout>
</FrameLayout>
</LinearLayout>
</FrameLayout>
It's normal behaviour and you are correct. the activity is recreated from scratch on rotation.
If you want something to persist. store it during onSaveInstanceState in the provided bundle.
then during onCreate check to see if the bundle is null, if it isn't, pull your data out and add the view elements again.
Alternatively you can fudge it and state in the manifest that your activity will handle orientation/configuration changes.

Categories