Android: populating Linear Layout programmatically, It gets extra space - android

I'm trying to populate a LinearLayout horizontally with some ImageViews programmatically. In horizontal directon, everything works very well, but it reserves extra space vertically what I don't want.
Here is the xml:
<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="wrap_content"
android:orientation="vertical"
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="es.uam.dadm.jacopo_grassi_connecta4.Settings" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/your_color" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/your_color_container" >
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/adv_color" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/adv_color_container" >
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sounds" />
<Switch
android:id="#+id/sounds_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
and here's the java code:
private PlayerDataSource playersdb;
private Player player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Bundle extras = getIntent().getExtras();
playersdb = new PlayerDataSource(this);
player = playersdb.getPlayer(extras.getString(Utils.PARAM_PLAYER_ID));
buildColors();
Switch sounds = (Switch)findViewById(R.id.sounds_switch);
sounds.setOnCheckedChangeListener(this);
sounds.setChecked(player.getSounds() == 0 ? false : true);
}
#Override
public void onClick(View v) {
Integer tag = (Integer) v.getTag(R.id.TAG_ADV);
if(tag == null){ //your color
tag = (Integer) v.getTag(R.id.TAG_YOU);
player.setColor(tag);
}else{ //adv color
player.setColorAdv(tag);
}
playersdb.updatePlayer(player);
buildColors();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
player.setSounds(1);
}else{
player.setSounds(0);
}
playersdb.updatePlayer(player);
}
private void buildColors(){
LinearLayout parent = (LinearLayout)findViewById(R.id.your_color_container);
parent.removeAllViewsInLayout();
for (int i = 0; i < 5; ++i) {
LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.weight = 0.2f;
ImageView v = new ImageView(this);
Integer drawable = null;
switch (i){
case 0:
drawable = R.drawable.red_piece;
break;
case 1:
drawable = R.drawable.yellow_piece;
break;
case 2:
drawable = R.drawable.green_piece;
break;
case 3:
drawable = R.drawable.purple_piece;
break;
case 4:
drawable = R.drawable.azure_piece;
break;
}
v.setLayoutParams(params);
v.setImageResource(drawable);
v.setTag(R.id.TAG_YOU, drawable);
v.setOnClickListener(this);
if (drawable.equals(player.getColor())) {
v.setBackgroundColor(getResources().getColor(R.color.azul));
}
parent.addView(v);
}
parent = (LinearLayout)findViewById(R.id.adv_color_container);
parent.removeAllViewsInLayout();
for (int i = 0; i < 5; ++i) {
LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.weight = 0.2f;
ImageView v = new ImageView(this);
Integer drawable = null;
switch (i){
case 0:
drawable = R.drawable.red_piece;
break;
case 1:
drawable = R.drawable.yellow_piece;
break;
case 2:
drawable = R.drawable.green_piece;
break;
case 3:
drawable = R.drawable.purple_piece;
break;
case 4:
drawable = R.drawable.azure_piece;
break;
}
v.setLayoutParams(params);
v.setImageResource(drawable);
v.setTag(R.id.TAG_ADV, drawable);
v.setOnClickListener(this);
if (drawable.equals(player.getColorAdv())) {
v.setBackgroundColor(getResources().getColor(R.color.azul));
}
parent.addView(v);
}
}
and that's the result:
Obviously, the images are perfect squares.
What am I doing wrong?

Does it work if you change the android:layout_height of your outer LinearLayout to "wrap_content"?

Try to make your LinearLayout.Params width & height to "LayoutParams.WRAP_CONTENT" & also height of linear layout in XML file

This is how to solve your problem.
(the below code should be added into your for loop before parent.addView(v)
You need to use a Runnable thread in order to get the Views width which will be set as the height at runtime or else you'll be trying to set the Height before you know the View's width because the layout hasn't been drawn yet.
v.post(new Runnable() {
#Override
public void run() {
LinearLayout.LayoutParams mParams;
mParams = (LinearLayout.LayoutParams) v.getLayoutParams();
mParams.height = v.getWidth();
v.setLayoutParams(mParams);
v.postInvalidate();
}
});
v.postInvalidate() is called to force the view to redraw while on a separate thread than the UI thread

Solved thanks to #Terence
Added
v.setAdjustViewBounds = true;

Try parent.addView(v, params);

Related

custom drag and drop

i am a begginer android develpoer and i am tring to build a small soiltare game.
for dragging the cards i implemented a custom viewgroup which is a "DragContainer" from one of the questions here.
my problem is that when i drag a linear layout. my linear layout holds the cards
with a - margin (to overlap the cards) but when i start the drag the dragged "shadow" is my layout without the margin.
here is an example
this is the start of the activity, the left is a linear layout with two children and also the right
when i start the drag this is what i see
as you can see the dragged "shadow" is bigger(without the - margin)
this is the code for the custom drag container(only the stuff that matters):
public boolean startDragChild(View child, ClipData data,
Object myLocalState, int flags) {
setDragTarget(child);
return child.startDrag(data, new EmptyDragShadowBuilder(child),
myLocalState, flags);
}
private void setDragTarget(View v) {
target = v;
onSetDragTarget(v);
}
/**
* this is similar to the constructor of DragShadowBuilder
*
* #param v
*/
protected void onSetDragTarget(View v) {
}
#Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mOnDrag && target != null) {
canvas.save();
drawDragShadow(canvas);
canvas.restore();
}
}
protected void drawDragShadow(Canvas canvas) {
int h = target.getHeight();
int w = target.getWidth();
canvas.translate(mDragX - w / 2, mDragY - h / 2);
target.draw(canvas);
}
I guess akon does not require the explanation but I would like to tell to the audience of the question.
The margins inside the LinearLayout should be intact as you would be moving ViewGroup itself, so it's children won't have any issue with it's design,
Code is also available on the Github
public class DragTestTwoActivity extends AppCompatActivity {
private LinearLayout source_linearLayout;
private LinearLayout destination_linearLayout;
private static final String TAG = "DragTestTwoActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drag_test_two);
initializeUI();
}
private void initializeUI() {
source_linearLayout = (LinearLayout) findViewById(R.id.DragTestTwoActivity_Source_LinearLayout);
destination_linearLayout = (LinearLayout) findViewById(R.id.DragTestActivityActivity_Destination_LinearLayout);
// source_linearLayout.setOnDragListener(new MyDragListener());
destination_linearLayout.setOnDragListener(new MyDragListener());
source_linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(source_linearLayout);
source_linearLayout.startDrag(data, shadowBuilder, source_linearLayout, 0);
return true;
}
});
}
private class MyDragListener implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
Log.d(TAG, "Drag has started");
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.d(TAG, "Drag has ended");
v.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(TAG, "Drag has entered");
break;
case DragEvent.ACTION_DRAG_LOCATION:
Log.d(TAG, "Drag location");
break;
case DragEvent.ACTION_DROP:
Log.d(TAG, "Drag has dropped");
View source_linear_Layout = (LinearLayout) event.getLocalState();
LinearLayout view = (LinearLayout) source_linear_Layout.getParent();
view.removeView(source_linear_Layout); // This will remove the imageView where it was
LinearLayout linearLayout = (LinearLayout) v;
if (v.getId() == R.id.DragTestActivityActivity_Source_LinearLayout) {
Log.d(TAG, "This is a source location");
} else if (v.getId() == R.id.DragTestActivityActivity_Destination_LinearLayout) {
Log.d(TAG, "This is a destination");
}
linearLayout.addView(source_linear_Layout); // this will add the ImageView to the new location where it was dropped.
source_linear_Layout.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_EXITED:
Log.d(TAG, "Drag has exited");
break;
}
return true;
}
}
}
activity_drag_test_two.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:orientation="vertical"
tools:context="activities.list.first.DragTestTwoActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="4sp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:background="#ABABAB"
android:orientation="vertical"
android:padding="4dp">
<LinearLayout
android:id="#+id/DragTestTwoActivity_Source_LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/DragTestTwoActivity_imageView"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_margin="4dp"
android:scaleType="centerInside"
android:src="#drawable/gohan" />
<ImageView
android:id="#+id/DragTestTwoActivity_imageView2"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_margin="4dp"
android:scaleType="centerInside"
android:src="#drawable/goku" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/DragTestActivityActivity_Destination_LinearLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:background="#CACACB"
android:orientation="vertical"
android:padding="4dp">
</LinearLayout>
</LinearLayout>
</LinearLayout>
Output
this is how it would look like...
Of course, you can use standart views for this purpose but it is irrational. It will better to use SurfaceView (or if you know OpenGL GLSurfaceView).

Android - How to convert DP to PX - density independent to absolute pixels

I have a situation wherein I need to add layouts at runtime as follows:
1. A Button layout is already defined in XML:
2. When the user clicks the Button, an EditText and another Button are dynamically added to the existing layout:
It works correctly on Gingerbread (Android 2.3.5):
And doesn't work on Kitkat (Android 4.4.2):
Does someone know a workaround for this problem ? Here's the code I've used:
public class MainActivity extends Activity {
private boolean comment = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.commentbutton);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
if(comment == true){
comment = false;
LinearLayout l = (LinearLayout)findViewById(R.id.comment_layout);
l.setOrientation(LinearLayout.VERTICAL);
final EditText e = new EditText(v.getContext());
e.setId(R.id.commentbox);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(250,100);
lp.setMargins(0, 20, 0, 0);
e.setLayoutParams(lp);
e.setSingleLine(true);
e.setImeOptions(EditorInfo.IME_ACTION_DONE);
l.addView(e);
final Button b = new Button(v.getContext());
b.setId(R.id.submitbutton);
lp = new LinearLayout.LayoutParams(150,33);
lp.setMargins(0, 20, 0, 0);
b.setLayoutParams(lp);
b.setText("Submit");
b.setTextColor(Color.BLACK);
b.setTypeface(null, Typeface.BOLD);
b.setBackgroundColor(Color.parseColor("#CCCCCC"));
b.setFocusable(true);
b.setFocusableInTouchMode(true);
l.addView(b);
e.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
b.performClick();
return true;
}
return false;
}
});
LinearLayout ll = new LinearLayout(v.getContext());
ll.setId(R.id.productbottomlayout);
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,25);
ll.setLayoutParams(lp);
ll.setFocusable(true);
ll.setFocusableInTouchMode(true);
l.addView(ll);
ll.requestFocus();
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
LinearLayout l = (LinearLayout) findViewById(R.id.comment_layout);
EditText e = (EditText) findViewById(R.id.commentbox);
l.removeView(e);
Button b = (Button) findViewById(R.id.submitbutton);
l.removeView(b);
LinearLayout ll = (LinearLayout) findViewById(R.id.productbottomlayout);
l.removeView(ll);
MainActivity.this.comment = true;
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here's the XML Layout:
<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:gravity="center"
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" >
<LinearLayout
android:id="#+id/comment_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="25dp"
android:layout_gravity="center"
android:gravity="center">
<Button
android:id="#+id/commentbutton"
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Add Comment"
android:textColor="#000000"
android:textStyle="bold"
android:background="#CCCCCC"
android:onClick="showCommentBox"/>
</LinearLayout>
</RelativeLayout>
Also, when we add layouts programmatically like this, we need to set an ID manually for each layout element.
I've done that. Here they are:
<resources>
<item type = "id" name = "commentbox"></item>
<item type = "id" name = "submitbutton"></item>
<item type="id" name="productbottomlayout"></item>
</resources>
The problem is that you are setting the dimension in a pixel measurement unit.
Use DP, or LayoutParams.WRAP_CONTENT to make your app scalable and responsive.
So, that's how I'll set my layoutParams:
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
Add this method and use it to convert all pixels to dpi:
public static int dpi(int i) {
Resources r = getResources();
int value = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, i,
r.getDisplayMetrics());
return value;
}
source: https://stackoverflow.com/a/6327095/1977021
// Try this way,hope this will help you to solve your problem...
Define this method in your class
public int convertSizeToDeviceDependent(int value) {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
return ((dm.densityDpi * value) / 160);
}
Try to replace this line:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(250,100);
With this:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(convertSizeToDeviceDependent(250),convertSizeToDeviceDependent(100));
Try to replace this line:
lp = new LinearLayout.LayoutParams(150,33);
With this:
lp = new LinearLayout.LayoutParams(convertSizeToDeviceDependent(150),convertSizeToDeviceDependent(33));
Try to replace this line:
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,25);
With this:
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,convertSizeToDeviceDependent(25));

How to programmatically display a view in center of another view

I have a buttonView1 and a customView1 that only draws a small circle. in my main_layout only buttonView1 is visible.
How can I programmatically display customView1 in center of buttonView1 when button is clicked.
attention: we dont want to change button background. we want to show a new view (customView or any other view like editText) on another view (button) when button is pressed.
layout code:
<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" >
<Button
android:id="#+id/buttonView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="102dp"
android:layout_marginTop="86dp"
android:text="#string/button_text" />
</RelativeLayout>
activity code
///...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.buttonView1);
mButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonView1:
// do sth here
break;
default:
break;
}
}
///...
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
yourView.setLayoutParams(layoutParams);
public void MoveView() {
float a = parent_view.getWidth() / 2;
final ValueAnimator positionAnimator =
ValueAnimator.ofFloat(current_view.getX(), a);
positionAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
positionAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float x = (Float) positionAnimator.getAnimatedValue();
current_view.setX(x);
}
});
positionAnimator.setDuration(100);
positionAnimator.start();
}
parent_view is the view in whose center you would like to place your current_view.
Hope that Helps.

Creating Multiple ImageButtons in a Single Activity Programatically

I have a single image myimage.png which is placed in my res-drawable folder.
I have to create 50 ImageButtons in an activity all using this same image.
And then when a user clicks i need to pop out a toast saying button number i was clicked.
Here's what I have done:
public class AllImageButtons extends Activity {
int screendimesionx;
int screendimesiony;
ImageButton imageButton;
ImageButton allImageButtons[] = new ImageButton[50];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allbuttonimages);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screendimesiony = metrics.heightPixels;
screendimesionx = metrics.widthPixels;
createButtonsAndAddListener();
}
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = (ImageButton) findViewById(R.id.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
}
}}
and then there is the associated xml file allbuttonimages.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/myimage" />
</LinearLayout>
This xml layout displays only the last ImageButton from the loop.
My Question:
How can i dynamically create all 50 ImageButtons from the same image in a single view ?
You are not adding the buttons to the parent .
use addView(yourImageButton) to add your image button to activity
The button that is visible now is the one in xml
You should create new imageButton using new
eg: ImageButton imgBtn = new ImageButton(this)
Then set the properties and addView to your parent Layout
You will not get 50 buttons with the one defined in xml
You have one button in layout and you are calling findViewById for that.
You need to create new buttons each time and add it to the linearlayout.
public void createButtonsAndAddListener() {
for (int i = 0; i < 50; i++) {
imageButton = new ImageButton(this);
imageButton.setImageResource(R.drawable.myimage);
float buttonimagey = imageButton.getDrawable().getBounds().height();
float buttonimagex = imageButton.getDrawable().getBounds().width();
float xspaceforeachbuttonimage = screendimesionx/50;
LayoutParams par = (LayoutParams)imageButton.getLayoutParams();
par.leftMargin = (int) (i*xspaceforeachbuttonimage);
par.topMargin = 0;
imageButton.setLayoutParams(par);
allImageButtons[i] = imageButton;
allImageButtons[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
((LinearLayout)findViewById(R.id.ll)).addView(imageButton);
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="#+id/ll">
</LinearLayout>
Your code wont add images to the layout. Get the parent layout in code and add images to it using addView. Between you do not need the image button in the xml. You can do some thing like this:
LinearLayout parent = (LinearLayout)findViewById(R.id.the_parent_layout);
for(int i = 0; i< 50; i++){
ImageButton image = new ImageButton(context);
//set whatever properties you want
//then add to the parent
parent.addView(image); // you can also specify the layout params here
}
Try This....
for (int i = 0; i < 50; i++) {
ImageButton b1 = new ImageButton(myrefmenu);
b1.setId(100 + i);
b1.setImageResource(R.drawable.imagename);
// b1.setText(adapt_objmenu.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.RIGHT_OF, b1.getId() - 1);
}
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(AllbuttonimagesForSelectionActivity.this,
"ImageButton is clicked!", Toast.LENGTH_SHORT)
.show();
}
});
b1.setLayoutParams(lp);
relative.addView(b1);
}

Changing EditText height and width on Runtime with some animation

I have Four EditText with different background.
It looks like this:
I want to cover full screen when a EditText is selected with That EditText. For that I need to change the EditText width and height with some animation on Runtime.
When selected It should look like this:
How can I change EditText size with animation on Runtime ?
ANSWER UPDATED :
use this code in drawable/animation_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false">
<translate android:fromXDelta="0%" android:toXDelta="100%" android:fromYDelta="0%" android:toYDelta="0%" android:duration="500" />
And set the animation to the edit text using :
Animation anim=AnimationUtils.loadAnimation( this, R.anim.righttoleft);
editText = (EditText)findViewById(R.id.editText1);
Display display = getWindowManager().getDefaultDisplay();
int width=display.getWidth();
int height = display.getHeight();
editText.setWidth(width);
editText.setHeight(height);
editText.startAnimation(anim);
I'm not sure if it can be done with Animations. In android view takes all space before animation finished, so you will see that other editTexts disappears and selected one slowly increasing. Here is rough example how to do it without standart animations, but changing weights in separate thread:
layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/ll0"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<EditText
android:id="#+id/et00"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="00" />
<EditText
android:id="#+id/et01"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="01" />
</LinearLayout>
<LinearLayout
android:id="#+id/ll1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal" >
<EditText
android:id="#+id/et10"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="10" />
<EditText
android:id="#+id/et11"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:text="11" />
</LinearLayout>
</LinearLayout>
and in code add actions on changing focus:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
OnFocusChangeListener focusListener = new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
LinearLayout parent = (LinearLayout) v.getParent();
EditText forDecresing = null;
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i) != v) {
forDecresing = (EditText) parent.getChildAt(i);
break;
}
}
LinearLayout pp = (LinearLayout) parent.getParent();
LinearLayout layoutForDecreasing = null;
for (int i = 0; i < pp.getChildCount(); i++) {
if (pp.getChildAt(i) != parent && pp.getChildAt(i) instanceof LinearLayout) {
layoutForDecreasing = (LinearLayout) pp.getChildAt(i);
break;
}
}
startAnimation((EditText) v, forDecresing, layoutForDecreasing, parent);
} else {
}
}
};
((EditText) findViewById(R.id.et00)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et01)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et11)).setOnFocusChangeListener(focusListener);
((EditText) findViewById(R.id.et10)).setOnFocusChangeListener(focusListener);
}
public void onBackPressed() {
setWeight(findViewById(R.id.et00), 1);
setWeight(findViewById(R.id.et01), 1);
setWeight(findViewById(R.id.et11), 1);
setWeight(findViewById(R.id.et10), 1);
setWeight(findViewById(R.id.ll1), 1);
setWeight(findViewById(R.id.ll0), 1);
}
Thread animationThread;
private void startAnimation(final EditText forIncreasing, final EditText forDecresing, final LinearLayout layoutForDecreasing,
final LinearLayout layoutForIncreasing) {
if (animationThread != null)
animationThread.interrupt();
animationThread = new Thread(new Runnable() {
#Override
public void run() {
int iterations = 0;
int maxIterations = 30;
setWeight(forIncreasing, maxIterations - 1);
setWeight(layoutForIncreasing, maxIterations - 1);
setWeight(forDecresing, maxIterations - 1);
setWeight(layoutForDecreasing, maxIterations - 1);
while (iterations < maxIterations) {
iterations++;
setWeight(forIncreasing, maxIterations - 1 + iterations);
setWeight(layoutForIncreasing, maxIterations - 1 + iterations);
setWeight(forDecresing, maxIterations - 1 - iterations);
setWeight(layoutForDecreasing, maxIterations - 1 - iterations);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return;
}
}
animationThread = null;
}
});
animationThread.start();
}
private void setWeight(final View view, final float weight) {
runOnUiThread(new Runnable() {
#Override
public void run() {
LayoutParams params = (LayoutParams) view.getLayoutParams();
params.weight = weight;
view.setLayoutParams(params);
}
});
}
I do not know if this is possible for you, but in this example you can add some more movements quite easy.
I do not recommend use it production, if only you have some other options.
I have tried to explain my Logic for your problem...i hope so it would work for you..
EditText editText = new EditText(this);
editText.setOnClickListener(new OnClickListener() {
public void onClick(){
// Before getSize was introduced (in API level 13), you could use
// the getWidth and getHeight methods that are now deprecated:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
editText.setWidth(width);
editText.setHeight(height);
}
}

Categories

Resources