I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ScrollView mainScrollView;
LinearLayout scrollViewContainer;
ArrayList<String> stringArr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);
stringArr = new ArrayList<String>();
String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
"The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
"in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
" use of this constructor is unnecessary since Strings are immutable.";
for(int ii = 0; ii < 10; ii++){
if(ii%2 == 0) {
stringArr.add(str1);
}else{
stringArr.add(str2);
}
}
Resources r = getResources();
float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
LinearLayoutCompat.LayoutParams textViewLayoutParams = new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
for(int ii = 0; ii < stringArr.size(); ii++){
TextView textView = new TextView(this);
textView.setTextSize(12f);
textView.setText(stringArr.get(ii));
textView.setLayoutParams(textViewLayoutParams);
textViewLayoutParams.setMargins(10,30,10,30);
textView.requestLayout();
scrollViewContainer.addView(textView);
}
}
}