Like I said, I want to add views to an Android LinearLayout, but it is not working. What am I doing wrong. I want to have them inserted like this:
[ Click Me ]
added_view_01
added_view_02
added_view_03
etc.
Here is what I have for activity_main.xml
<?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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="addRow"/>
<LinearLayout
android:id="@+id/my_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom"/>
</LinearLayout>
And here is what I have for MainActivity.java
public class MainActivity extends AppCompatActivity {
private static int iterator = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addRow(View view){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
StringBuffer stringBuffer = new StringBuffer();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.my_layout);
TextView textView = new TextView(this);
textView.setLayoutParams(layoutParams);
textView.setTextSize(34);
stringBuffer.append("Timestamp: ");
stringBuffer.append(sdf.format(new Date()));
textView.setText(stringBuffer.toString());
linearLayout.addView(textView, iterator);
iterator++;
}
}
Of course, if I change linearLayout.addView(textView, iterator);
to linearLayout.addView(textView, 0);
, it replaces the view at position 0, but it never appends the new view. How do I get it to keep appending a new view?
Thanks
You should at least be seeing one view. But it takes up the whole screen when you add it.
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
Try changing the height parameter to WRAP_CONTENT
.