I am populating a viewgroup using a for loop and assigning IDs based on the iteration of the for loop. Something like :
For(int i = 0; i<=listLength; i++){
ImageView iv = new Imageview(this);
RelativeLayout r = (RelativeLayout) findViewById(R.id.relativeLayout);
iv.setId(i);
iv.setImageResource(R.drawable.imageResource);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(10, 10);
if(i==0){
params.addRule(RelativeLayout.CENTER_IN_PARENT);
}
else{
params.addRule(RelativeLayout.ABOVE, i-1);
}
iv.setLayoutParams(params);
r.addView(iv);
}
However, when I try to place the next view relative to that ID, the view always appears in the top left corner of the parent view. The first view is in the right place but the others don't seem to know where the previous view is.
I think that it is because the scope of iv.setId(); is limited to that iteration of the for loop. Is that the reason?
Related
I want to add ImageViews to a layout from an ArrayList, but when there are too many views,
it starts to show some delay because it first loads every image and then applies them to the view. I need to know if there is a way to add them one by one to avoid delay.
I'm using this code.
ArrayList<String> pictures;
ImageView iv;
LinearLayout container;
for (int i = 0; i < pictures.size(); i++) {
LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
iv = new ImageView(getActivity());
iv.setLayoutParams(params);
iv.setImageBitmap(pictures.get(i));
container.addView(iv);
}
I am adding horizontalScrollView programatically , but when I try to do horizontalScrollView.getMeasuredWidth() it keeps returning 0.
void addCategory(String catTitle) {
mVideos = mShows.get(catTitle);
LinearLayout theLayout = (LinearLayout)findViewById(R.id.activitymain);
TextView textview=(TextView)getLayoutInflater().inflate(R.layout.categorytitle,null);
textview.setTextColor(Color.CYAN);
textview.setTextSize(20);
textview.setText(catTitle);
HorizontalScrollView horizontalScroll = new HorizontalScrollView (this,null);
LinearLayout LL = new LinearLayout(this);
LL.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
LL.setLayoutParams(LLParams);
HorizontalGalleryAdapter adapter = new HorizontalGalleryAdapter(this,mVideos);
for (int i = 0; i < adapter.getCount(); i++) {
View item = adapter.getView(i, null, null);
LL.addView(item);
}
horizontalScroll.addView(LL);
int maxScrollX = horizontalScroll.getChildAt(0).getMeasuredWidth()-horizontalScroll.getMeasuredWidth();
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Reset...");
String max= String.valueOf(maxScrollX);
Ok, I see the problem. You create a HorizontalScrollView, add a child to it, and then immediately try to get its measured width.
You cannot do this. You must add the horizontal scroll view to an existing already-drawn view in your activity first, because otherwise it doesn't have set dimensions yet.
Think about how would it know how many pixels WRAP_CONTENT will set the dimension to before its laid out in your view? If you add it to an existing, already-laid-out view in your activity, then that WRAP_CONTENT will actually get converted to some height.
It looks like you kind-of have a loop - horizontalScroll's dimensions depend on its content (WRAP_CONTENT), yet the content's (LinearLayout's) dimensions depend on the horizontalScroll's dimensions. This does not make sense. Perhaps try MATCH_PARENT for at least the width dimensions of your horizontal scroll view. Then, make sure to not look at dimensions until the view has been drawn.
Have a look into typical usage example for HorizontalScrollView:
// read a view's width
private int viewWidth(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
return view.getMeasuredWidth();
}
....
void getTableRowHeaderCellWidth(){
int tableAChildCount = ((TableRow)this.tableA.getChildAt(0)).getChildCount();
int tableBChildCount = ((TableRow)this.tableB.getChildAt(0)).getChildCount();;
for(int x=0; x<(tableAChildCount+tableBChildCount); x++){
if(x==0){
this.headerCellsWidth[x] = this.viewWidth(((TableRow)this.tableA.getChildAt(0)).getChildAt(x));
}else{
this.headerCellsWidth[x] = this.viewWidth(((TableRow)this.tableB.getChildAt(0)).getChildAt(x-1));
}
}
}
You can also check full details from this nice tutorial: The code of a Ninja.
I tried to use below code, but the textviews do not change line after it reach the end of screen.
RelativeLayout ll = (RelativeLayout)findViewById(R.id.viewObj);
int lastid=0;
for (int i=0; i<100; i++) {
String teststr = " hello ";
TextView textView2 = new TextView(this);
textView2.setId(i+1);
textView2.setTextSize(30);
textView2.setBackgroundColor(Color.GREEN);
textView2.setTextColor(Color.RED);
textView2.setTypeface(Typeface.MONOSPACE);
textView2.setText(teststr+String.valueOf(i));
if (i>0)
{
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.RIGHT_OF, lastid);
ll.addView(textView2, lay);
} else {
ll.addView(textView2);
};
lastid = textView2.getId();
}
However, I dont know how to determine when to change line. I just keep on putting new textview to the right of the last one created. Can anyone tell me the correct logic to do the task? many thanks.
Easy fix. Switch to a dynamically-created LinearLayout, and set its orientation to vertical:
lay.setOrientation(LinearLayout.VERTICAL);
I have created two imageViews promatically as shown below:
public void createImageViews(Integer count){
ImageView[] imageViewArray = new ImageView[count];
for (int i = 0; i < count; i++ ) {
imageViewArray[i] = new ImageView(getBaseContext());
imageViewArray[i].setId(i); // unique property for every imageView
if(i==0){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imageViewArray[i].setLayoutParams(params);
imageViewArray[i].setBackgroundResource(imagesForIv[i]);
_UIRLParent.addView(imageViewArray[i]);
Log.v("first", "first"+i);
}
else if(i < 3){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i].getId());
imageViewArray[i].setBackgroundResource(imagesForIv[i]);
_UIRLParent.addView(imageViewArray[i],params);
Log.v("second", "second"+i);
}
}
I just need to place the second imageView toRightOf first imageView. Can someone help me. This is eating away a lot of my time.
try https://stackoverflow.com/a/5191159/1436931
you are using wrong index values.
at line
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i].getId());
you aligning current image RIGHT of current image. :)
you need to track the index of last imageView id i.e left Image view
you need something like this
params.addRule(RelativeLayout.RIGHT_OF,imageViewArray[i-1].getId());
I'm creating a button dynamically. The number of button is depend on the size of arraylist. the problem is, after creating the button I will add to the layout using addview method. The problem is I'm using linear layout, as by default orientation for linear layout is horizontal, so the button will fill the layout horizontally. Because of that some of the button is not visible. What I'm trying to achieve is something look like this
My code is like below:
Button[] tv = new Button[arraylist.size()];
for(int i=0;i<arraylist.size();i++){
tv[i] = new Button(getApplicationContext());
tv[i].setText(arraylist.get(i).toString());
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
linearlayout.addView(tv[i]);
}
If I set the orientation of linear layout to vertical the button will fill vertically. So if there any solution to create the button dynamically and fill the layout both horizontal and vertical as shown by image.
There is not a canned layout in the SDK that does exactly what you are aiming for (i.e. lay out as many children horizontally as will fit, then flow to the next line to lay out some more), so you will need to create a custom ViewGroup that accomplishes this purpose. Luckily for you, Romain Guy created one live on-screen during a presentation at Devoxx.
Here is a link to that presentation video.
Here is a link to the sample code and slides.
HTH
After 2 days struggling thinking bout this problem finally I've found the solution. I've try put all my contact list, store it in arraylist and create button for each element and I'm quite satisfy with the result after display on the screen. Here is how I do the trick. I really appreciate for any comment from others.
variable declaration;
int currWidth;
int currCounter;
boolean isNewLine;
LinkedList<HashMap<String,Object>> button;
ArrayList<String> nameNumber = new ArrayList<String>();
contactWrapper = (LinearLayout) findViewById(R.id.multiple_selection);
create button onClick event;
for(int i=0;i<nameNumber.size();i++){
tv[i] = new Button(getApplicationContext());
String[] namePhone = nameNumber.get(i).toString().split("##");
phoneNumber.add(namePhone[1]);
tv[i].setText(namePhone[0]);
tv[i].setTag(namePhone[1]);
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
tv[i].measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("button", tv[i]);
map.put("width", tv[i].getMeasuredWidth());
button.add(map);
}
drawLayout();
drawlayout method is where I add button and arrange accordingly to fit the layout;
public void drawLayout(){
int counter=0;
contactWrapper.setOrientation(LinearLayout.VERTICAL);
currCounter=0;
currWidth=0;
isNewLine=false;
LinearLayout[] row = new LinearLayout[nameNumber.size()];
row[currCounter] = new LinearLayout(getApplicationContext());
#SuppressWarnings("rawtypes")
Iterator it = button.iterator();
for(int i = 0; i<button.size(); i++){
it.next();
row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
currWidth += Integer.parseInt(button.get(i).get("width").toString());
if(isNewLine){
if(currWidth < contactWrapper.getWidth()){
row[currCounter].addView((View) button.get(i).get("button"));
if(!it.hasNext()){
contactWrapper.addView(row[currCounter]);
}else{
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}else{
if(currWidth < contactWrapper.getWidth()){
if(!it.hasNext()){
row[currCounter].addView((View) button.get(i).get("button"));
contactWrapper.addView(row[currCounter]);
}else{
row[currCounter].addView((View) button.get(i).get("button"));
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}
counter++;
}
}
this code quite messy + I'm not fully utilize the size of array for
LinearLayout[] row = new LinearLayout[nameNumber.size()];
but it work for me.
use TableLayout instead of LinearLayout this is tutorial hope this will help you to get the idea
Does you set android:layout_width="fill_parent"?
Do this if you don't.
Well, you can try using more sophisticated way. You can create horizontal linear layout, and add buttons to it. Every time you're attempting to add new button, you check if there is place for it, by finding difference between layout's and buttons widths.
Each time your horizontal layout is filled, you add it to another vertical layout, and create another horizontal layout to store buttons left.
I used that trick in my apps.
try this its working fine
this.row = (LinearLayout)findViewById(R.id.tags);
this.row.setOrientation(LinearLayout.VERTICAL);
LinearLayout one = new LinearLayout(this);
//get the size of the screen
Display display = getWindowManager().getDefaultDisplay();
this.screenWidth = display.getWidth(); // deprecated
this.screenHeight = display.getHeight();// depreceted
for(int i=0; i<6; i++) {
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
this.button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
if(i==0) {
this.button.setText("Muhammad Aamir");
} else if(i==1) {
this.button.setText("Ahsan");
} else if(i==2) {
this.button.setText("Mujahid");
} else if(i==3) {
this.button.setText("Waqas");
} else if(i==4) {
this.button.setText("Ali");
} else {
this.button.setText("Ahmer");
}
//get the size of the button text
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(button.getTextSize());
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
float size = mPaint.measureText(button.getText().toString(), 0, button.getText().toString().length());
size = size+14;
this.totalTextWidth += size;
if(totalTextWidth < screenWidth) {
one.addView(button);
} else {
this.row.addView(one);
one = new LinearLayout(this);
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
one.addView(button);
this.totalTextWidth = size;
}
}
this.row.addView(one);
}