how to programmatically create an imageView with id and src parameters? - android

The following works, but I want to eliminate the xml so that I can change the image programmatically:
Java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p6_touch);
ImageView floatImage = (ImageView) findViewById(R.id.p6_imageView);
floatImage.setOnTouchListener(this);
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/background_black" >
<ImageView
android:id="#+id/p6_imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="matrix"
android:src="#drawable/p6_trail_map" >
</ImageView>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:onClick="showFlashlight"
android:src="#drawable/legend_block24" />
</FrameLayout>

In the documentation there is a table that maps XML to Java.
For instance: android:src is equivalent to setImageResource().
You will need to check the inherited table for attributes from any super class.
For instance: android:id is equivalent to setId().
width, height, and gravity are all set in a LayoutParams object and passed to setLayoutParams().
Understand that not every XML attribute has a matching Java method (and vica versa), but all of the attributes you are using do.
An Example, let's call this file activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/background_black" >
<!-- We'll add this missing ImageView back in with Java -->
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:onClick="showFlashlight"
android:src="#drawable/legend_block24" />
</FrameLayout>
Now in our Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Let's create the missing ImageView
ImageView image = new ImageView(this);
// Now the layout parameters, these are a little tricky at first
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT);
image.setScaleType(ImageView.ScaleType.MATRIX);
image.setImageResource(R.drawable.p6_trail_map);
image.setOnTouchListener(this);
// Let's get the root layout and add our ImageView
FrameLayout layout = (FrameLayout) findViewById(R.id.root);
layout.addView(image, 0, params);
}

Related

How to change the margin of an "included" layout programatically

I have a LinearLayout inside which I am including a different layout. Something like this
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:visibility="gone"
tools:visibility="visible">
<include
layout="#layout/new_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="4dp"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:layout_weight="1"/>
</LinearLayout>
Now what I would like to do is, to programmatically change the "marginBottom" of the included layout (new_layout). How can I do that?
I tried calling various LayoutParams and tried changing the margin, but not sure if it is the right approach. Any help greatly appreciated.
Thanks
Try this.. Make the Linear layout using your id
LinearLayout ll =(LinearLayout) findViewById(R.id.linear_layout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 20);
layoutParams.setMargins(left,top,right,bottom);
where you can pass the value in setMargins
and if you want to input value in dp.. Try this
public void setMargin(Context con,ViewGroup.LayoutParams params,int dp) {
final float scale = con.getResources().getDisplayMetrics().density;
// convert the DP into pixel
int pixel = (int)(dp * scale + 0.5f);
ViewGroup.MarginLayoutParams s =(ViewGroup.MarginLayoutParams)params;
s.setMargins(pixel,pixel,pixel,pixel);
yourView.setLayoutParams(params);
}
where you can pass your layout params
include.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:id="#+id/include_layout">
<ImageView android:layout_width="90dp"
android:layout_height="90dp"
android:src="#drawable/cross" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<include layout="#layout/include"/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:padding="10dp" />
</LinearLayout>
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LinearLayout included=(LinearLayout)findViewById(R.id.include_layout);
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(Math.round(10), Math.round(10), Math.round(10), Math.round(10));
//set margin...
included.setLayoutParams(params);
}
}
You should not directly change or modify margins in the <include> tag. This tag is just adding the layout resource in the current view hierarchy without adding an extra parent view container.
So essentially what you want to do is set margins on the root view container of the "included layout". That is you should directly call findViewById() for the root view and set all of your margins on it pro grammatically and as the included view's parent is a Linear-layout you should use
LinerLayout.LayoutParams params = (LinerLayout.LayoutParams) includedRootView.getLayoutParams();
params.setMargins();
includedViewRoot.setLayoutParams(params);`
You can change it by dimensions also
res/values/dimens.xml
res/values-small/dimens.xml
res/values-normal/dimens.xml
res/values-xlarge/dimens.xml
I think this code helpful...
include.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:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" >
</ImageView>
</LinearLayout>
activity_main.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="match_parent" >
<include
android:id="#+id/include_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
layout="#layout/include" />
</LinearLayout>
MainActivity
package com.example.stackdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout include_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
include_layout = (LinearLayout) findViewById(R.id.include_layout);
#SuppressWarnings("deprecation")
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.setMargins(0, 0, 0, 100);
include_layout.setLayoutParams(layoutParams);
}
}

dynamically set LinearLayout height/width in relativelayout

i have a linearLayout inside a RelativeLayout. I need to be able to set the height of the linearlayout dynamically depending on the screen dimensions. Im having some difficulties.
how can i achieve this?
MAIN :
public class MainActivity extends Activity {
LinearLayout L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
L=(LinearLayout)findViewById(R.id.top);
L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400));
}
}
XML:
<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"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:id="#+id/top"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</LinearLayout>
When you set layout params, it needs to be that of the parent.
Switch:
L.setLayoutParams(new LinearLayout.LayoutParams(1080, 400));
To:
L.setLayoutParams(new RelativeLayout.LayoutParams(1080, 400));
in your LinearLayout, just set
android:layout_height="0dp"
android:layout_weight="1"
As Justin answered
L.setLayoutParams(new RelativeLayout.LayoutParams(1080, 400));
You might also need, if you have already set the layout
L.requestLayout();
In Kotlin you can do the following:
L.layoutParams = RelativeLayout.LayoutParams(1080, 400)
And then call L.requestLayout() to apply changes

Creating a layout programatically using XML elements

I've programmed one of my layouts programatically. And when I tried to implement it in XML I couldn't make it work. It crashes with NullPointerException and I really do not know why.
This is my 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:orientation="vertical"
tools:context=".DisplayMessageActivity" >
<ImageView
android:id="#+id/canal_1"
android:contentDescription="#string/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="canal1_Click"
android:src="#drawable/pestanya_seleccionada" />
</RelativeLayout>
And what I'm trying is:
ImageView canal1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* layout prinicpal */
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
canal1 = (ImageView) findViewById(R.id.canal_1);
relativeLayout.addView(canal1);
setContentView(relativeLayout, rlp);
}
It crashes at relativeLayout.addView(canal1);
I don't why this fails. In my head everything should run fine.
Thanks for reading and hope you can help me ;)
Kind regards,
Raúl
You have not set content of the xml layout to the screen and you are finding the id of the ImageView. This is causing NPE.
canal1 = (ImageView) findViewById(R.id.canal_1);
The above statement will cause nullpointerexception since you have not set the layout and your are trying to find the id form the defined in the xml file.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
//add other ui elements to the root layout ie RelativeLayout
}
<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:id="#+id/relativeLayout"// relative layout id
android:orientation="vertical"
tools:context=".DisplayMessageActivity" >
<ImageView
android:id="#+id/canal_1"
android:contentDescription="#string/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="canal1_Click"
android:src="#drawable/pestanya_seleccionada" />
</RelativeLayout>

nullpointer exception with a new layout

I am having the next problem:
i have an activity with its own layout called camera_layout, when i
had all my layout in that file all went ok,
now to display some of
the views over my extended surfaceview i have added another layout
with the code for those views
in order to add this linearlayout to
the frame layout that contains my extended surfaceview after i add
the the surfaceview, on my oncreate method i set some views using
findviewbyid,
at this moment all is ok
after this on my onpreview
method i get a nullpointer exception at that views i set.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("Function", "onCreate iniciado");
setContentView(R.layout.camera_layout);
//tFrame=new Target_Frame(this);
cViewActual=(CView)findViewById(R.id.cViewActual);
bestMatchCView=(CView)findViewById(R.id.cViewBestMatch);
actualCLabelTextView=(TextView)findViewById(R.id.textViewActualC);
bestMatchLabelTextView=(TextView)findViewById(R.id.BestMatchtextViewLabel);
coNametextView=(TextView)findViewById(R.id.textViewCName);
mCamera=getCameraInstance();
mPreview=new CameraPreview(this,mCamera,cViewActual,bestMatchCView,colorNametextView);
FrameLayout preview=(FrameLayout)findViewById(R.id.camera_preview);
hasFlash=checkFlash(this);
flashActivated=false;
flashButton=new ImageButton(this);
flashButton.setImageResource(R.drawable.flashofficon);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
params.gravity=Gravity.CENTER;
flashButton.setLayoutParams(params);
addListenerToFlashButton();
preview.addView(mPreview);
preview.addView(flashButton);
View itemLayout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_bar_layout,null,false);
preview.addView(itemLayout);
}
My camera layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" >
<Button
android:id="#+id/button1"
android:layout_width="5dp"
android:layout_height="5dp"
android:layout_gravity="top|left"
android:text="Button" />
</FrameLayout>
</LinearLayout>
And my layout for the views I want to put over the surfaceview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="113dp"
android:layout_height="fill_parent"
android:gravity="right"
android:id="#+id/itemToolLayout"
android:orientation="vertical">
<TextView
android:id="#+id/textViewActualC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Actual Color"
android:textAppearance="?android:attr/textAppearanceMedium" />
<com.example.prueba.CView
android:id="#+id/cViewActual"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/BestMatchtextViewLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Best Match"
android:textAppearance="?android:attr/textAppearanceMedium" />
<com.example.prueba.CView
android:id="#+id/cViewBestMatch"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/textViewCName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Color Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture" />
</LinearLayout>
use
actualCLabelTextView=(TextView)findViewById(R.id.textViewActualC);
instead of
actualCLabelTextView=(TextView)findViewById(R.id.textViewActual);
because TextView with textViewActual id not exist in current Activity layout it is textViewActualC
and always attach relevant logcat results with question if application is crashing
I have changed some things that were wrong and i post here the new code, the problem was that my cViewActual and all the views after this are null, because they aren´t on my principal layout file, i thought that after inflate a view->itemlayout with the layout of my secondary layout file i could access to the views of that layout using findViewById, but it seems that this doesn´t find the views, now i change some thing to use findViewById on itemlayout view and now i can find the views of the secondary layout
Here is my modified code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("Function", "onCreate iniciado");
setContentView(R.layout.camera_layout);
FrameLayout preview=(FrameLayout)findViewById(R.id.camera_preview);
hasFlash=checkFlash(this);
flashActivated=false;
flashButton=new ImageButton(this);
flashButton.setImageResource(R.drawable.flashofficon);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
params.gravity=Gravity.CENTER;
flashButton.setLayoutParams(params);
addListenerToFlashButton();
View itemLayout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_bar_layout,null,false);
tFrame=new Target_Frame(this);
cViewActual=(ColorView)itemLayout.findViewById(R.id.colorViewActual);
bestMatchCView=(ColorView)itemLayout.findViewById(R.id.colorViewBestMatch);
actualColorLabelTextView=(TextView)itemLayout.findViewById(R.id.textViewActualColor);
bestMatchLabelTextView=(TextView)itemLayout.findViewById(R.id.BestMatchtextViewLabel);
colorNametextView=(TextView)itemLayout.findViewById(R.id.textViewColorName);
mCamera=getCameraInstance();
mPreview=new CameraPreview(this, mCamera,cViewActual,bestMatchCView,colorNametextView);
preview.addView(mPreview);
preview.addView(flashButton);
preview.addView(itemLayout);
}

How can i write this layout code in my Android Activity?

I wish to create a custom layout out for my sample application. Previously i used the xml layout for User interface, but now i wish to create the application using custom (without using xml layout). I used the below code in my xml, but i change this xml layout to custom code i can't implement (i don't have knowledge how to do this). How can i write this layout code in my Activity?. Any one could you please help me to solve this. Thanks in advance.
<?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" >
<ScrollView
android:id="#+id/webviewscroll"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/webviewlinear"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/webviewframe1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<WebView
android:id="#+id/webview1"
android:layout_width="fill_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp" >
</WebView>
<ImageView
android:id="#+id/webviewimage1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/one" >
</ImageView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/webviewframe2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<WebView
android:id="#+id/webview2"
android:layout_width="fill_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp" >
</WebView>
<ImageView
android:id="#+id/webviewimage2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/two" >
</ImageView>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
As you want to create layout at run-time, you can do this way:
RelativeLayout layout1 = new RelativeLayout(this);
ImageView imgView1 = new imgView1(this);
layout1.addView(imgView1); // added ImageView into the RelativeLayout
do this kind of process for creating and adding widgets.
LinearLayout ll1,ll2;
ScrollView sv = new ScrollView(this);
RelativeLayout rl1,rl2;
WebView wv1,wv2;
ImageView iv1,iv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int LHeightWrap = LinearLayout.LayoutParams.WRAP_CONTENT;
int LWidthWrap = LinearLayout.LayoutParams.WRAP_CONTENT;
int LHeightFill = LinearLayout.LayoutParams.FILL_PARENT;
int LWidthFill = LinearLayout.LayoutParams.FILL_PARENT;
int RHeightWrap = RelativeLayout.LayoutParams.WRAP_CONTENT;
int RWidthWrap = RelativeLayout.LayoutParams.WRAP_CONTENT;
int RHeightFill = RelativeLayout.LayoutParams.FILL_PARENT;
int RWidthFill = RelativeLayout.LayoutParams.FILL_PARENT;
wv1 = new WebView(this);
iv1 = new ImageView(this);
rl1.addView(wv1,RWidthWrap,RHeightWrap);
rl1.addView(iv1,RWidthWrap,RHeightWrap);
wv2 = new WebView(this);
iv2 = new ImageView(this);
rl2.addView(wv2,RWidthWrap,RHeightWrap);
rl2.addView(iv2,RWidthWrap,RHeightWrap);
ll2.addView(rl1);
ll2.addView(rl2);
sv.addView(ll2);
ll1.addView(ll2);
You can do somthing like this. You can also set properties of any component using native code.

Categories

Resources