[Converting Activity code to fragment]Dynamically adding images to LinearLayout in Fragment - android

I Have already done this in activity and I will provide part of that code as well. Basically I have a linear layout inside HorizontalScroll View and I want to add imageViews to it dynamically. The activity code for this is below and it works perfectly fine all I want is to have exact same functionality for 1 of my fragments as well. XML for the code is given below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="5dp"
tools:context="com.example.scrolls_tabs.OneFragment"
android:background="#drawable/wooden_back">
<HorizontalScrollView
android:id="#+id/HorizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:background="#00ffffff"
android:scrollbars="none">
<LinearLayout
android:id="#+id/MainLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/imgLayout1"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
</HorizontalScrollView>
and code for this that works perfectly in activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout =(RelativeLayout)findViewById(R.id.activity_main);
layout.setBackgroundResource(R.drawable.wooden_back);
// Bitmap bdrawable = new Bitmap(this.getResources().getIdentifier("drawable/wood_back", "id", getPackageName()));
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenHeight = displaymetrics.heightPixels;
int screenWidth = displaymetrics.widthPixels;
int imgHeight = (int) (screenHeight* 0.30);
int imgWidth = (int) (screenWidth* 0.25);
for (int j=1; j<10; j++)
{
final int b1=j;
create_img1("drawable/a"+j, b1, imgHeight, imgWidth);
ImageView drag = (ImageView)findViewById(b1);
dragAndDropImage(drag, "drawable/c"+j);
}
ImageView imgh=(ImageView)findViewById(R.id.bottomlinear);
imgh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Bundle localBundle = new Bundle();
localBundle.putInt("Item #1", item1);
localBundle.putInt("Item #2", item2);
localBundle.putInt("Item #3", item3);
localBundle.putInt("Item #4", item4);
localBundle.putInt("Item #5", item5);
localBundle.putInt("Item #6", item6);
localBundle.putInt("Item #7", item7);
localBundle.putInt("Item #8", item8);
localBundle.putInt("Item #9", item9);
Intent i = new Intent(getApplicationContext(),test_activity.class);
i.putExtras(localBundle);
startActivityForResult(i, 1);
}
});
}
void create_img1(String ss, int ID, int H, int W)
{
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.imgLayout1);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
parms.gravity = Gravity.CENTER;
parms.setMargins(20, 0, 20, 0);
final ImageView imageView = new ImageView(this);
imageView.setLayoutParams(parms);
int id = getResources().getIdentifier(ss, "id", getPackageName());
imageView.setImageResource(id);
linearLayout.addView(imageView);
imageView.setId(ID);
imageView.getLayoutParams().height = H;
imageView.getLayoutParams().width = W;
}
This is basically me looking for a solution where I get to do the same thing in fragments that I have already done in activity. I'm very new to android so anything helpful is appreciated.
Current Fragment code which is not working.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
fa = super.getActivity();
ll = (LinearLayout) inflater.inflate(R.layout.fragment_one, container, false);
int imgHeight = 50;
int imgWidth = 50;
for (int j=1; j<10; j++)
{
final int b1=j;
create_img1("drawable/a"+j, b1, imgHeight, imgWidth);
}
return ll;
}
void create_img1(String ss, int ID, int H, int W)
{
LinearLayout linearLayout = (LinearLayout) ll.findViewById(R.id.imgLayout1);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
parms.gravity = Gravity.CENTER;
parms.setMargins(20, 0, 20, 0);
final ImageView imageView = new ImageView(getActivity());
imageView.setLayoutParams(parms);
//int id = getResources().getIdentifier(ss, "id", getPackageName());
imageView.setImageResource(R.drawable.a1);
linearLayout.addView(imageView);
imageView.setId(ID);
//imageView.getLayoutParams().height = H;
//imageView.getLayoutParams().width = W;
}
}

you should add img view to linear layout like below
void create_img1(String ss, int ID, int H, int W)
{
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.imgLayout1);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
parms.gravity = Gravity.CENTER;
parms.setMargins(20, 0, 20, 0);
final ImageView imageView = new ImageView(this);
imageView.setLayoutParams(parms);
int id = getResources().getIdentifier(ss, "id", getPackageName());
imageView.setImageResource(id);
imageView.setId(ID);
imageView.getLayoutParams().height = H;
imageView.getLayoutParams().width = W;
**linearLayout.addView(imageView);**
}

Related

slowly scroll in page

I want to make a view slowly scrolls into mobile page, first like this:
then like this:
the view with red background slowly scrolls into mobile page.
Here is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_clean_complete"
android:layout_width="140dp"
android:layout_height="140dp"
android:layout_marginTop="80dp"
android:src="#mipmap/img_clean_completed_ok"
android:layout_centerHorizontal="true"/>
<RelativeLayout
android:id="#+id/layout_btm"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="288dp">
<TextView
android:text="Hello World"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
Here is the code:
public class MainActivity extends AppCompatActivity {
private RelativeLayout layoutBtm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutBtm = findViewById(R.id.layout_btm);
int topMargin = getHeightPixels();
ViewGroup.MarginLayoutParams marginLayoutParams =
new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(this, 288));
marginLayoutParams.topMargin = topMargin;
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(marginLayoutParams);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutBtm.setLayoutParams(layoutParams2);
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(layoutBtm, "translationY", -dip2px(this, 288));
objectAnimator.setDuration(1000);
objectAnimator.start();
}
private int getHeightPixels(){
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
return dm.heightPixels;
}
private int getStatusBarHeight(Activity activity){
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
Field field = clazz.getField("status_bar_height");
int dpHeight = Integer.parseInt(field.get(object).toString());
return activity.getResources().getDimensionPixelSize(dpHeight);
} catch (Exception e) {
return 0;
}
}
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
It seems to be fine. But after the red view scrolls in, there is some space left at the bottom.The page doesn't change its height automatically
Finally I know how to solve this problem. I edit the code of change the translationY of the view to change the top margin of the view.Here is the code after change:
public class MainActivity extends AppCompatActivity {
private RelativeLayout layoutBtm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutBtm = findViewById(R.id.layout_btm);
int topMargin = getHeightPixels();
ViewGroup.MarginLayoutParams marginLayoutParams =
new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(this, 288));
marginLayoutParams.topMargin = topMargin;
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(marginLayoutParams);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutBtm.setLayoutParams(layoutParams2);
ValueAnimator animator = ValueAnimator.ofInt(getHeightPixels(), getHeightPixels() - getStatusBarHeight(this) -dip2px(this, 288));
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
int currentValue = (int) animator.getAnimatedValue();
ViewGroup.MarginLayoutParams marginLayoutParams =
new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(MainActivity.this, 288));
marginLayoutParams.topMargin = currentValue;
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(marginLayoutParams);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutBtm.setLayoutParams(layoutParams2);
layoutBtm.requestLayout();
}
});
animator.setDuration(1000);
animator.start();
}
private int getHeightPixels(){
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
return dm.heightPixels;
}
private int getStatusBarHeight(Activity activity){
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
Field field = clazz.getField("status_bar_height");
int dpHeight = Integer.parseInt(field.get(object).toString());
return activity.getResources().getDimensionPixelSize(dpHeight);
} catch (Exception e) {
return 0;
}
}
private int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}

Android, overlapping imageViews

I am creating programatically ImageViews and dragging them in the same layout.
I would like to disable overlapping for this ImageView. Is there a setting to be applied to disable overlap when I create every ImageView programatically or something else ?
public class MainActivity extends ActionBarActivity {
private int offset_x = 0;
private int offset_y = 0;
RelativeLayout canvas;
LinearLayout buttonslayout;
boolean isselected = false;
View selected_item = null;
int test1,test2;
Button save,newdoor,newwindow,rotate;
TextView xcoord,ycoord;
//static final int SNAP_GRID_INTERVAL = 43;
static final int SNAP_GRID_INTERVAL = 44;
static final int SNAP_GRID_INTERVAL2 = 25;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
canvas = (RelativeLayout) findViewById(R.id.container2);
ViewGroup vg = (ViewGroup)findViewById(R.id.container3);
//buttonslayout = (LinearLayout) findViewById(R.id.container3);
save = (Button) findViewById(R.id.savebtn);
newdoor = (Button) findViewById(R.id.btnnewdoor);
newwindow = (Button) findViewById(R.id.btnnewwindow);
xcoord = (TextView) findViewById(R.id.xcoord);
ycoord = (TextView) findViewById(R.id.ycoord);
rotate = (Button) findViewById(R.id.rotate);
newwindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final int lungime = 66;
final int inaltime = 20;
final int []lastcoords = new int[2];
final int canvasWidth = canvas.getWidth();
final int canvasHeight = canvas.getHeight();
RelativeLayout mylayout = (RelativeLayout) findViewById(R.id.container2);
final View canvas = ((View) v.getParent());
final int []coordwall = new int[2];
mylayout.getLocationInWindow(coordwall);
final ImageView image = new ImageView(getBaseContext());
image.setBackgroundResource(R.drawable.element_window);
mylayout.addView(image);
image.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
offset_x = (int)event.getX();
offset_y = (int)event.getY();
selected_item = v;
isselected = true;
xcoord.setText("X: "+lastcoords[0]);
ycoord.setText("Y: "+lastcoords[1]);
Log.i("test","Isselected = "+isselected);
break;
default:
break;
}
return false;
}
});
rotate.setOnClickListener(new View.OnClickListener() {
int grad=0;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(grad!=1)
{
image.setRotation(90);
grad=1;
}
else
{
image.setRotation(180);
grad=0;
}
}
});
mylayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
MarginLayoutParams marginParams = new MarginLayoutParams(v.getLayoutParams());
switch(event.getAction())
{
case MotionEvent.ACTION_UP:
isselected = false;
Log.i("test","Isselected = "+isselected);
break;
case MotionEvent.ACTION_MOVE:
if(isselected == true)
{
View canvas = ((View) v.getParent());
final int width = v.getWidth() / 2, height = v.getHeight() / 2;
int x = (int)event.getX() - offset_x;
int y = (int)event.getY() - offset_y;
int w = getWindowManager().getDefaultDisplay().getWidth() - 100;
int h = getWindowManager().getDefaultDisplay().getHeight() - 100;
int rawX = (int) event.getRawX(), rawY = (int) event.getRawY();
int x_coord = (int) event.getRawX() - coordwall[0] - width;
int y_coord = (int) event.getRawY() - coordwall[1] - height;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
new ViewGroup.MarginLayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
if (rawY < coordwall[1] + inaltime / 2)
lp.topMargin = 0;
else
if (rawY >= coordwall[1] + canvasHeight - inaltime )
lp.topMargin = canvasHeight - inaltime*2;
else
lp.topMargin = y / SNAP_GRID_INTERVAL * SNAP_GRID_INTERVAL;
if(rawX < coordwall[0] + lungime / 2)
lp.leftMargin = 0;
else
if(rawX >= coordwall[0] + canvasWidth - lungime)
{
lp.leftMargin = canvasWidth - lungime*2;
Log.i("arry","leftmargin = " + lp.leftMargin);
}
else
lp.leftMargin = x / SNAP_GRID_INTERVAL * SNAP_GRID_INTERVAL;
lastcoords[0] = lp.leftMargin;
lastcoords[1] = lp.topMargin;
xcoord.setText("X: "+lp.leftMargin);
ycoord.setText("Y: "+lp.topMargin);
lp.setMargins(lp.leftMargin, lp.topMargin, 0, 0);
selected_item.setLayoutParams(lp);
}
break;
default:
break;
}
return true;
}
});
}
});
And the xml:
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="horizontal"
tools:context="com.example.draganddrop.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:id="#+id/container3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#848484"
android:orientation="vertical" >
<Button
android:id="#+id/savebtn"
style="#drawable/new_wall"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_wall"
android:textSize="13sp" />
<Button
android:id="#+id/btnnewwindow"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_window"
android:textSize="13sp" />
<Button
android:id="#+id/btnnewdoor"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:background="#drawable/new_door"
android:textSize="14sp" />
<TextView
android:id="#+id/xcoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="X: " />
<TextView
android:id="#+id/ycoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Y: " />
<Button
android:id="#+id/rotate"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rotate" />
</LinearLayout>
<RelativeLayout
android:id="#+id/container2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
</RelativeLayout>
</LinearLayout>
It is not very clear what exactly You want to do, but if I am understand You the right way, You want to set some ImageViews to a layout programmatically? Why are Your Views overlapping? I think You have to set the layout Paramaters for Your view container:
//after onCreate in the activity, create the LinearLayout (for example)
//and set the LayoutParams, if You have no one declared in Your xml
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
//then create the imageView, set the image inside and add it to the container
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.your_image);
imageView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
linearLayout.addView(imageView);
//set all as content
setContentView(linearLayout);
Have You done it in this way? If not, try it, also if You want to set multiple imageViews or some other Layout, You have to play a little bit with the LayoutParams.

ImageView pushed out from screen

I'm playing around in Android and what I'm trying to achieve is a 10x10tile boardgame.
I want to read size and width of screen and then I want a square in the middle with a textViews above and below.
This is what I've done so far:
public void init(){
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}else{
Display d = w.getDefaultDisplay();
screenWidth = d.getWidth();
screenHeight = d.getHeight();
}
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView TVtop = new TextView(this.getApplicationContext());
TVtop.setHeight((screenHeight-screenWidth)/2);
TVtop.setWidth(screenWidth);
TVtop.setText("TOP");
TextView TVbot = new TextView(this.getApplicationContext());
TVbot.setHeight((screenHeight-screenWidth)/2);
TVbot.setWidth(screenWidth);
TVbot.setText("BOT");
TableLayout tableLayout = new TableLayout(this.getApplicationContext());
//Make a cube
LayoutParams tableParams = new LayoutParams(screenWidth, screenWidth);
tableLayout.setLayoutParams(tableParams);
//Populate tableLayout
for(int i = 0; i < nrOfTiles; i++){
TableRow tableRow = new TableRow(this.getApplicationContext());
for(int j = 0; j < nrOfTiles; j++){
ImageView imgView = new ImageView(this.getApplicationContext());
imgView.setImageResource(R.drawable.cell);
tableRow.addView(imgView);
}
tableLayout.addView(tableRow);
}
linearLayout.addView(TVtop);
linearLayout.addView(tableLayout);
linearLayout.addView(TVbot);
}
}
I've tried diffrent layoutparams but nothing seems to get the work done. :S
BR
Personally, I would use a RelativeLayout and setMargins for the items.
While not a direct answer to your question, the following code will display 15 icons in three rows. This should be enough to explain and get you started.
The main activity.
public class MainActivity extends Activity {
private int mWidth;
private int mTile;
private int mColMax = 5;
private Context mContext;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
// the screen width is need to work out the tile size
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Point size = new Point();
w.getDefaultDisplay().getSize(size);
mWidth = size.x;
}else{
mWidth = w.getDefaultDisplay().getWidth();
}
// how wide (and high) each icon will be to fit the screen.
mTile = (mWidth / mColMax);
setContentView(R.layout.activity_main);
// layout the icons
initUI();
}
/**
* Layout 15 icon images in three rows dynamically.
*/
private void initUI() {
// this is the layout from the XML
ViewGroup layout = (ViewGroup) findViewById(R.id.main_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int i = 0;
int row = 0;
int col = 0;
do {
params = new RelativeLayout.LayoutParams(mTile,mTile);
params.setMargins((col * mTile), (row * mTile), 0, 0);
iv = new ImageView(mContext);
iv.setAdjustViewBounds(true);
iv.setScaleType(ScaleType.FIT_CENTER);
iv.setImageResource(R.drawable.ic_launcher);
iv.setLayoutParams(params);
layout.addView(iv);
if (col == mColMax) {
row++;
col = 0;
} else {
col++;
}
} while (++i <= 16);
}
}
And the layout XML.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>

Views within custom layout won't show

I'm creating a custom linear layout to hold two image views.
I first thought that the layout is not showing at all but I then set its background to black to check if the layout is being inflated and it did. Then understood that the problem is the image views, they simply not showing.
Thanks in advance :-)
This is the class:
public class LoginIcons extends LinearLayout {
private ImageView mImageViewLogo;
private ImageView mImageViewIcons;
private View mView;
boolean test = false;
public LoginIcons(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public LoginIcons(Context context) {
super(context);
init();
}
private void init() {
setOrientation(LinearLayout.VERTICAL);
mImageViewLogo = new ImageView(this.getContext());
mImageViewIcons = new ImageView(this.getContext());
mView = new View(getContext());
LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mImageViewLogo.setLayoutParams(params);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = (int)LocalSettingsHelper.dpToPx(getContext(), 20);
mImageViewIcons.setLayoutParams(params);
params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = (int)LocalSettingsHelper.dpToPx(getContext(), 10);
mView.setLayoutParams(params);
mImageViewLogo.setImageResource(R.drawable.splash_logo_placeholder);
mImageViewIcons.setImageResource(R.drawable.login_icons);
mImageViewIcons.setBackgroundColor(Color.BLACK);
mImageViewLogo.setBackgroundColor(Color.BLACK);
addView(mView);
addView(mImageViewLogo);
addView(mImageViewIcons);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
setViewsDimensions();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
}
private void setViewsDimensions() {
LinearLayout parent = (LinearLayout) mImageViewLogo.getParent();
int screenWidth = LocalSettingsHelper.getScreenWidth(getContext());
// 0.375 percent
int imgDim = (int) ((double) screenWidth * 0.32);
int iconsWidth = (int) ((double) screenWidth * 0.5);
LinearLayout.LayoutParams params = (LayoutParams) mImageViewLogo
.getLayoutParams();
params.width = imgDim;
params.height = imgDim;
mImageViewLogo.setLayoutParams(params);
params = (LayoutParams) mImageViewIcons.getLayoutParams();
params.width = iconsWidth;
mImageViewIcons.setLayoutParams(params);
}
}
And this is the xml:
<?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:background="#color/HeaderBackground"
android:orientation="vertical" >
<Button
android:id="#+id/button_ok"
style="#style/LoginOkButtonStyle"
android:background="#drawable/blue_button_background_selector"
android:text="#string/ok" />
<com.example.me.entities.views.LoginIcons
android:id="#+id/loginIcons"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</com.example.me.entities.views.LoginIcons>
</LinearLayout>
It seems that the View object acted like match_parent and had height of nearly 400 pixels. This caused the image views to drop outside the boundaries of the screen.
Once I removed the View the image views turned up.

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.

Categories

Resources