Creating an XML for Dynamically created Elements - android

I want XML for the TextViews and EditTexts created dynamically. Some blogs suggest that there are some Third Party Libraries that can do that but I wasn't able to find one. I am basically creating TextViews & EditTexts dynamically in my code on a button click.
Code:
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
for (int x = 0; x < 1; x++) {
Display display = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth() / 3;
TextView et1 = new TextView(this);
et1.setBackgroundColor(color.transparent);
et1.setText("Untitled");
et1.setGravity(Gravity.LEFT);
EditText et = new EditText(this);
et.setHint("Click to add");
et.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
LayoutParams lp1 = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LayoutParams lp2 = new LayoutParams(width,
LayoutParams.WRAP_CONTENT);
// lp1.addRule(RelativeLayout.BELOW, et1.getId());
linearLayout1.addView(et1, lp2);
linearLayout1.addView(et, lp2);
XML:
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/addImage" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/addEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/scrollView1"
android:text="Edit" />
The question is, how do I achieve the XML for the TextView & EditText as a String value? Do I give them tags and ids statically in the code or is there any other way?
public static final void writeMapXml(Map val, String name, XmlSerializer out)
throws XmlPullParserException, java.io.IOException
{
if (val == null) {
out.startTag(null, "TextView");
out.endTag(null, "TextView");
return;
}
Set s = val.entrySet();
Iterator i = s.iterator();
out.startTag(null, "TextView");
if (name != null) {
out.attribute(null, "name", "TextView");
}
out.endTag(null, "TextView");
}

XMLSerializer provided by android itself is enough to make dynamic XMLs.

Related

setOrientation is not working for LinearLayout programatically

I am add dynamic data to the LinearLayout. default I declared as vertical orientation in xml. But I need to load horizontal data by programmatic way, Here set Orientation is not working.
LinearLayout llQuestionLayout = (LinearLayout) findViewById(R.id.ll_question_layout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llQuestionLayout.setLayoutParams(layoutParams);
llQuestionLayout.setOrientation(LinearLayout.HORIZONTAL);
private void populateLikert() {
if(llQuestionLayout.getChildCount() > 0) {
llQuestionLayout.removeAllViews();
}
RadioGroup radioGroup = new RadioGroup(this);
for(int i =0; i < 5; i++) {
RadioButton radioButton = (RadioButton) LayoutInflater.from(this).inflate(R.layout.likert_radio_button, null, false);
radioButton.setText("" + (i + 1));
radioGroup.addView(radioButton);
}
llQuestionLayout.addView(radioGroup);
}
<LinearLayout
android:id="#+id/ll_question_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:orientation="vertical"/>
Please suggest correct answer.

Create buttons programmatically goes new line

I created a layout which programmatically created buttons (see code). With this layout I have a column of buttons, but I would create something like the picture below. I tried something with linear layout but the buttons didn't go to new line automatically and didn't show, so I change it to table layout. How can I create something like the picture programmatically?
Thank you.
protected TableLayout layout;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout = (TableLayout) findViewById(R.id.workflows_activity_layout);
private void createButton() {
loading.setVisibility(View.VISIBLE);
layout.removeAllViews();
if (items.length == 0) {
TableRow row = new TableRow(this);
TextView no_item = new TextView(this);
no_questions.setText("there are no items");
no_questions.setTextSize(35);
row.addView(no_item);
layout.addView(row);
} else {
for (int i = 0; i < items.length; i++) {
TableRow row = new TableRow(this);
final Button btn = new Button(this);
TextView tw = new TextView(this);
tw.setText(items[i].getName());
tw.setTextSize(25);
btn.setBackgroundResource(R.drawable.button_image);
btn.setId(i);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int btn_selected = btn.getId();
Intent openItempage = new Intent(MainActivity.this, ItemsActivity.class);
startActivity(openItempage);
}
});
row.addView(btn);
row.addView(tw);
layout.addView(row, params);
items_buttons.add(btn);
items_nameText.add(tw);
}
}
loading.setVisibility(View.GONE);
}
There's an easy way to achieve what you want. Look at this code:
<?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="match_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<TableLayout
android:id="#+id/tab_lay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:stretchColumns="*"
android:gravity="center_vertical" />
TabLayout tab_lay = (TableLayout)view.findViewById(R.id.tab_lay);
for(int i = 1; i <= 4; ){
TableRow a = new TableRow(getActivity());
TableRow.LayoutParams param = new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1.0f);
a.setLayoutParams(param);
a.setGravity(Gravity.CENTER_VERTICAL);
for(int y = 0; (y < 2) && (i <= 4); y++) {
Button x = new Button(getActivity());
x.setText("Text " + i);
x.setGravity(Gravity.CENTER);
TableRow.LayoutParams par = new TableRow.LayoutParams(y);
x.setLayoutParams(par);
int ids = i;
x.setId(ids);
x.setOnClickListener(this);
a.addView(x);
i++;
}
tab_lay.addView(a);
}
If you want more buttons, then just change 4 which is compare to i to your value. Hope I help.
You can implement this using labraries, for instance
FlowLayout
Usage:
<com.wefika.flowlayout.FlowLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="start|top">
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lorem ipsum" />
</com.wefika.flowlayout.FlowLayout>
Another solution is:
AndroidFlowLayout
Usage:
<com.liangfeizc.flowlayout.FlowLayout
android:id="#+id/flow_layout"
flowlayout:vertical_spacing="10dp"
flowlayout:horizontal_spacing="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

Android set layout programmatically results in wrong display

I have this LinearLayout in my Layout, if I copy that in my XML layout file I get another line with those three elements and everythings looks as expected. Now I try to add this LinearLayout and its child elements programmatically which works but looks differently and all wrong. The button seems to have the right width but the height is too low and the other two elements are hardly visible with wrong height and width.
This is the layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/editTextValueComposition"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.94"
android:ems="10"
android:hint="#string/valueHint"
android:inputType="numberDecimal" >
</EditText>
<Spinner
android:id="#+id/compositionSelector"
android:layout_width="176dp"
android:layout_height="wrap_content"
android:layout_weight="0.06" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addComposition"
android:text="#string/add" />
</LinearLayout>
And this is my code:
public void addComposition(View view) {
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
EditText valueEdit = new EditText(this);
valueEdit.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0.94f));
valueEdit.setHint(R.string.valueHint);
valueEdit.setEms(10);
linearLayout.addView(valueEdit);
Spinner compositionSelector = new Spinner(this);
compositionSelector.setLayoutParams(new TableLayout.LayoutParams(dpToPx(176), LayoutParams.WRAP_CONTENT, 0.06f));
ArrayAdapter<CharSequence> adapterComp = ArrayAdapter.createFromResource(
this, R.array.compositionTypes,
android.R.layout.simple_spinner_item);
adapterComp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
compositionSelector.setAdapter(adapterComp);
linearLayout.addView(compositionSelector);
Button addCompoButton = new Button(this);
addCompoButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addCompoButton.setText(R.string.add);
addCompoButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
addItem(v);
}
});
linearLayout.addView(addCompoButton);
LinearLayout addItemLayout = (LinearLayout) findViewById(R.id.screenAddItem);
int index = addItemLayout.indexOfChild(findViewById(R.id.button1));
addItemLayout.addView(linearLayout, index);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getBaseContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
Try to use LinearLayout.LayoutParams instead of TableLayout.LayoutParams

How to align these 2 buttons next to each other programmatically in Android?

I have written this piece of code. But it is not giving the proper result. Please let me know where is the mistake. And I don't want to use Linear Layout.
Here is the xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_relativeLayout1"
android:orientation="horizontal"
android:background="#ffffff">
</RelativeLayout>
</LinearLayout>
String[] but = {"Hello", "Bye"};
int buttonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customLayout = (RelativeLayout) findViewById(R.id.custom_relativeLayout1);
//customLayout is object of relativelayout.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (butArray[i].getId() != 1)
{
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
else
{
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
}
}
RelativeLayout.RIGHT_OFhoryzontally or vertically align?
so for vertically
Btnparams.addRule(RelativeLayout.BELOW, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
or for horizontally
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
customLayout.addView(butArray[i], Btnparams);
instead of
Btnparams.addRule(RelativeLayout.RIGHT_OF, butArray[i-1].getId());
butArray[i].setLayoutParams(Btnparams);
customLayout.addView(butArray[i]);
LinearLayout is very nice to use if you want do dynamically add Views and scale them the same. For example if you want to add buttons and have max 3 buttons per row, you can also use another LinearLayout to make a new row.
I 'abuse' the LinearLayout row and a Button for layoutparams templating.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_root"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll_row1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"/>
<Button
android:id="#+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"/>
</LinearLayout>
</LinearLayout>
Example code:
// Get LL and template params
LinearLayout root = (LinearLayout) findViewById(R.id.ll_root);
LinearLayout row1 = (LinearLayout) findViewById(R.id.ll_row1);
ViewGroup.LayoutParams llRowParams = row1.getLayoutParams();
ViewGroup.LayoutParams btnParams = findViewById(R.id.btn1).getLayoutParams();
// Make new button
Button newBtn = new Button(context);
newBtn.setLayoutParams(btnParams);
newBtn.setText("Button 3");
// Add button to row1
row1.addView(newBtn);
// Add new row
LinearLayout row2 = new LinearLayout(context);
row2.setLayoutParams(llRowParams);
root.addView(row2);
// TODO: add buttons to new row
// TODO: some logic to decide between adding to row or creating new row and adding button
Note: code is not tested, but you should get the idea.
buttonCount = but.length;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Button [] butArray = new Button[buttonCount];
for (int i = 0; i < 2; i++)
{
butArray[i] = new Button(this);
butArray[i].setLayoutParams(params);
RelativeLayout.LayoutParams Btnparams = (RelativeLayout.LayoutParams) butArray[i].getLayoutParams();
butArray[i].setText(but[i]);
butArray[i].setId(i+1); // Setting the ids
butArray[i].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_launcher, 0, 0);
butArray[i].setBackgroundColor(Color.TRANSPARENT);
if (i != 0) {
Btnparams.addRule(RelativeLayout.RIGHT_OF, i-1);
}
customLayout.addView(butArray[i], Btnparams);
}

Android HorizontalScrollView does not display all the child views

I have an android activity which contains a horizontal list view. Below is the layout for it:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id ="#+id/topMostLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grey">
<HorizontalScrollView
android:id ="#+id/horScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
>
<LinearLayout
android:id ="#+id/dateRibbon"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:gravity="center"
>
</LinearLayout>
</HorizontalScrollView>
<TextView
android:id="#+id/line"
android:paddingTop="5dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:background ="#37000000"
android:layout_below="#id/horScrollView"
/>
<LinearLayout
android:id="#+id/bottom_control_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_above="#id/bottom_control_bar"
android:layout_below="#id/line" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/bottom_control_bar"
android:layout_below="#id/horScrollView"
android:text="#string/tasks_empty" />
</RelativeLayout>
The problem is when I add views to the linearlayout inside the horizontalscrollview, it will not scroll fully to the right, so the rightmost child view is invisible to the user. I am adding textviews to the linearlayout. Below is the code for where the linear layout gets populated:
LinearLayout dateRibbon = FindViewById<LinearLayout>(Resource.Id.dateRibbon);
dateRibbon.RemoveAllViews();
TextView tView;
m_dateRibbonTextViews = new List<TextView>();
m_dateRibbonDates = new List<DateTime>();
int currentJobId = Telecetera.Connect.JobLibrary.JobData.Job.GetCurrentJobID();
int defaultCurrentJobID = Telecetera.Connect.JobLibrary.JobData.Job.SYSDIR_CURRENTJOB_DEFAULT;
Telecetera.Connect.JobLibrary.JobData.JobDetailsList jobDetailsList;
int i = -1;
foreach (DateTime date in jobsByDay.Keys)
{
++i;
jobDetailsList = jobsByDay[date];
tView = new TextView(this);
tView.Gravity = GravityFlags.CenterHorizontal;
tView.Text = GetDateDisplayString(date);
tView.SetTextSize(Android.Util.ComplexUnitType.Sp, 18);
tView.SetPadding(10, 0, 10, 0);
if (currentJobId != defaultCurrentJobID && jobDetailsList.GetByJobID(currentJobId) != null)
{
m_indicesDaysWithCurrentJob.Add(i);
tView.SetBackgroundColor(Android.Graphics.Color.Cyan);
}
else
{
tView.SetBackgroundColor(Android.Graphics.Color.White);
}
tView.Click += new EventHandler(tView_Click);
dateRibbon.AddView(tView);
m_dateRibbonTextViews.Add(tView);
m_dateRibbonDates.Add(date);
tView = new TextView(this);
tView.SetPadding(2, 0, 2, 0);
tView.SetBackgroundColor(Resources.GetColor(Resource.Color.grey));
dateRibbon.AddView(tView);
}
Any hints as to why it does not completely scroll to the right would be appreciated!
Thanks.
I was able to solve it by removing the
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
lines.
you can set padding to linear layout here's my code which show's the textview at center and give some space at start and at the end of view.
lLayTwo.setPadding((center - 2 - centerScreenChildLeft), 0, (center - 2 - centerScreenChildRight), 0);
private void addSubMenu(ArrayList<String> list,String mainMenu){
this.mainMenu = mainMenu;
lLayTwo.removeAllViews();
mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(mViewPlain));
menu = list;
Log.d(TAG, "meulist "+menu.size());
range = list.size() * 2 + 1;
Log.d(TAG, "range "+range);
int menuItem = 0;
for ( int i = 0; i < range; i++ ) {
if ( i % 2 == 0 ){
View txt = new View(MCSDistrictMainActivity.this);
txt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
txt.setBackgroundResource(R.drawable.line);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 3, 0, 0);
lLayTwo.addView(txt,params);
}else{
TextView txt = new TextView(MCSDistrictMainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(parentChildWidh, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 8, 0, 5);
params.gravity = Gravity.CENTER;
txt.setText(menu.get(menuItem));
txt.setTag(menu.get(menuItem));
txt.setTextColor(getResources().getColor(R.color.violet));
txt.setTextSize(15f);
txt.setGravity(Gravity.CENTER_HORIZONTAL);
menuItem += 1;
lLayTwo.addView(txt,params);
}
}
Log.d(TAG, "llayout Two "+lLayTwo.getChildCount()+" width "+parentChildWidh+" LEFT "+parentChildLeft);
int left = parentChildLeft;
int width = parentChildWidh;
int centerTab = 1 + hsvLowerTab.getWidth() / 2;
Log.d(TAG, "Measures left "+left+" width "+width+" center "+centerTab+" all "+( left + width -centerTab ));
//(left + width/2)-centerTab
hsvLowerTab.scrollTo((left + width/2)-centerTab, 0);
hsvLowerTab.dispatchTouchEvent (MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(),
MotionEvent.ACTION_UP,(left + width/2)-centerTab, 0, 0));
}

Categories

Resources