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

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));

Related

Android: How to preload views?

I am trying to make a game where in the start menu, when a button is clicked, a story event will be happening. There will be different stories when the button is clicked depending on the character the player is using,so I don't want to make a billion different activities/fragments for the stories.
I have two layouts that I want to switch within the same activity.
To switch from layout 1 to layout 2, I tried to add layout 2 to layout 1, and also tried ViewFlipper , but when I try to switch from Layout 1 to layout 2, the TextView in layout 2 says "New text" first before turning into what I want it to say. The textbox, which is supposed to be at the bottom, appears at the top first and then jumps to the bottom
I've also tried using threads to have layout 2 preload but that just messes up layout 2. So what should I do?
Here is my class for the story
public class Story extends FrameLayout {
String[][] story;
int H;
int W;
int L;
int index =0;
TextView text;
ImageView character;
View v;
Story(Context context,String[][]story,int length){
super(context);
this.story=story;
this.L = length;
init(context);
}
public void init(Context context) {
LayoutInflater l = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = l.inflate(R.layout.story, this, true);
final RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final FrameLayout.LayoutParams imageParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
text = (TextView) v.findViewById(R.id.story);
character = (ImageView) v.findViewById(R.id.chara);
final RelativeLayout textBox = (RelativeLayout) v.findViewById(R.id.textbox);
textBox.post(new Runnable() {
#Override
public void run() {
H = textBox.getHeight();
W = textBox.getWidth();
textParams.setMargins(W / 12, H / 8, W / 10, H / 8);
text.setLayoutParams(textParams);
text.setText(story[index][0]);
}
});
v.post(new Runnable() {
#Override
public void run() {
int h = v.getHeight();
imageParams.setMargins(W / 7 * 2, h / 10, 0, H / 3);
character.setLayoutParams(imageParams);
character.setImageResource(Integer.parseInt(story[index][1]));
}
});
}
}
XML for the story
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chara"
android:scaleType="fitStart"
android:adjustViewBounds="true"
/>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textbox"
android:layout_gravity="bottom">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/vntextbox"
android:adjustViewBounds="true"
android:scaleType="fitEnd">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/story" />
</RelativeLayout>
</merge>
For each character, they have a method that returns their story, eg for a particular character :
public class Player extends ImageView {
Context context;
Player (Context context){
super(context);
this.context=context;
}
public Story getIntro(){
int normal = R.drawable.normal;
int serious = R.drawable.serious;
int happy = R.drawable.happy;
final int length = 8;
String[][] story = // a story
final Story s = new Story(context, story, l);
s.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do some stuff
}
});
return s;
}
}
And here is where the story is used
public class StartMenu extends AppCompatActivity {
#Override
protected void onCreate(final Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.startmenu);
final RelativeLayout r = (RelativeLayout)findViewById(R.id.startscreen);
final Button b =new Button(this);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here I want to do something like this: (doesn't work due to problems described above)
Player p = new Player(StartMenu.this);
Story s = p.getIntro();
r.removeAllViews();
r.addView(s);
}
});
Try to leave the text space empty on your .xml and just fill it when you're creating the activity (if it is dynamic). It will solve the text change flick.
About the two layouts, search about Fragments.

Android: populating Linear Layout programmatically, It gets extra space

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);

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);
}

Adding multiple image views programmatically

I'm basically trying to achieve drag&drop feature..
What i'm trying is that i provides sequence of images on the screen, if i click on any image available in images row that will be added to the Mains screen. But i'm getting problem that when i add new view into the Main Screen then all the other views also moved to top left corner.
Can you please tell me what is the problem...? Or kindly suggest me a tutorial or link where i can find solution.... or how to achieve this ?
I'm using Framelayout, So that i also achieve images overlapping...
This is the class in which all code is working:
public class drag extends Activity implements OnClickListener, OnTouchListener
{
ImageView img1;
Button btn,btn2;
FrameLayout layout;
LayoutParams params;
ImageView im , im2, im3 ,im4;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (FrameLayout) findViewById(R.id.vg);
layout.setDrawingCacheEnabled(true);
im = (ImageView)findViewById(R.id.img1);
im.setDrawingCacheEnabled(true);
im.setOnTouchListener(this);
im.setOnClickListener(this);
btn = (Button)findViewById(R.id.btn1);
btn.setDrawingCacheEnabled(true);
btn.setOnClickListener(this);
btn.setOnTouchListener(this);
btn2 = (Button)findViewById(R.id.btn2);
btn2.setDrawingCacheEnabled(true);
btn2.setOnClickListener(this);
btn2.setOnTouchListener(this);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
im2 = new ImageView(drag.this);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
im2.setImageBitmap(bm);
im2.setOnTouchListener(drag.this);
im2.setOnClickListener(drag.this);
layout.addView(im2, params);
}
});
btn2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
saveImage(bm);
}
});
}
public void saveImage(Bitmap myBitmap)
{
MediaStore.Images.Media.insertImage(getContentResolver(), myBitmap, "mmsImage" , "mmsimage");
}
int l, t, r, b;
int oldLeft, oldTop;
PointF p, curr;
#Override
public boolean onTouch(View view, MotionEvent me)
{
if (me.getAction() == MotionEvent.ACTION_DOWN)
{
//status = START_DRAGGING;
Log.i("status"," AAA dOWN");
img1 = new ImageView(this);
view.setDrawingCacheEnabled(true);
Bitmap mmsImage = Bitmap.createBitmap(view.getDrawingCache());
img1.setImageBitmap(mmsImage);
img1.setOnTouchListener(drag.this);
img1.setOnClickListener(drag.this);
oldLeft = (int)view.getLeft();
oldTop = (int)view.getTop();
p = new PointF(me.getRawX(), me.getRawY());
}
if (me.getAction() == MotionEvent.ACTION_MOVE)
{
Log.i("status"," AAA draging");
int xDiff = (int)(me.getRawX() - p.x);
int yDiff = (int)(me.getRawY() - p.y);
p.x = me.getRawX();
p.y = me.getRawY();
l = view.getLeft();
t = view.getTop();
r = view.getRight();
b = view.getBottom();
view.layout(l + xDiff, t + yDiff , r + xDiff, b + yDiff);
}
if (me.getAction() == MotionEvent.ACTION_UP)
{
Log.i("status"," AAA UP");
//captureUserMove(view);
}
return false;
}
}
Here is the XML :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/vg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white" >
<ImageView
android:id="#+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</FrameLayout>
You set params, but don't specify how to position the added view. Try this:
In onCreate()
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.LEFT | Gravity.TOP; // you need this for margins to work
In the click listener:
// your x and y where you want the new view
params.leftMargin = x;
params.topMargin = y;
Putting
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
inside
#Override
public void onClick(View v)
{
}
will work.

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