I just want to click to button and to change the Background image. here is my different codes
array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="image">
<item>#drawable/photo</item>
<item>#drawable/photo1</item>
<item>#drawable/photo2</item>
<item>#drawable/photo3</item>
<item>#drawable/photo4</item>
</string-array>
</resources>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_above="#+id/back"
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"
android:background="#drawable/photo"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="146dp"
android:text="Button" />
</RelativeLayout>
and here is my activity code:
final LinearLayout background = (LinearLayout) findViewById(R.id.back);
Button button = (Button) findViewById(R.id.button1);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
final Random random = new Random();
button.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v) {
int randomInt = random.nextInt(myImages.length());
background.setBackgroundResource(myImages.getResourceId(randomInt,-1));
int drawableID = myImages.getResourceId(randomInt,-1);
background.setBackgroundResource(drawableID);
}
});
it doesn't work , can you help me
Thanks in advance
In xml, you are using RelativeLayout, but in activity code, you are LinearLayout.
You are casting wrong layout in your code. You have taken the RelativeLayout in your xml file where as you are casting it into LinearLayout in your java file.
In your java file change the LinearLayout to RelativeLayout.
final LinearLayout background = (LinearLayout) findViewById(R.id.back);
write this:
final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
If the case is not the LinearLayout do this:
Change the definition of your array to
final String[] myImages = res.getStringArray(R.array.image);
And then, replace your onClick method for this:
public void onClick(View v) {
int randomInt = random.nextInt(myImages.length);
int drawableID = myImages.getResources().getIdentifier(myImages[randomInt], "drawable", this.getPackageName());
background.setBackgroundResource(drawableID);
}
Related
I am having problem getting a layout's ID.
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_img1" >
</LinearLayout>
.java file
#Override
protected void onCreate(Bundle savedStateInstance) {
super.onCreate(savedStateInstance);
setContentView(R.layout.splash);
int imgId[] = new int[] { R.drawable.splash_img1, R.drawable.splash_img2 };
Random random = new Random();
int result = random.nextInt(imgId.length);
LinearLayout layout = (LinearLayout) findViewById(R.layout.splash);
layout.setBackgroundDrawable(getResources().getDrawable(imgId[result]));
}
Whenever I run this, I get a Gradle build error of "undefined layout".
you can get the layout by R.id.layout_id.
add id to your layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/splash_layout" // <-- this to your code.
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_img1" >
</LinearLayout>
add this to your .java file
#Override
protected void onCreate(Bundle savedStateInstance) {
super.onCreate(savedStateInstance);
setContentView(R.layout.splash);
int imgId[] = new int[] { R.drawable.splash_img1, R.drawable.splash_img2 };
Random random = new Random();
int result = random.nextInt(imgId.length);
// edit this part.
LinearLayout layout = (LinearLayout) findViewById(R.id.splash_layout);
layout.setBackgroundDrawable(getResources().getDrawable(imgId[result]));
Hope this helps :)
I want to add more LinearLayout in a empty one when I press "add button".
When I press the first time "it works", the empty LinearLayout show that I want but if I press the button again don't work ( LogCat show me that occurs a NullPointerException). I see that its not create a new one LinearLayout below the previous one and no idea how solve it.
Let me show you part of my code:
First, I created
static int ID=0;
...
LinearLayout mLayout []= new LinearLayout[10];
...
OnCreate:
...
mLayout[ID] = (LinearLayout) findViewById(R.id.linearLayout_expandir);
...
Then:
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener() {
#Override
public void onClick(View v) {
mLayout[ID].addView(createNewTextView("Contain: ", ID));
mLayout[ID].addView(createNewEditText(ID));
mLayout[ID].addView(createNewTextView("Nº Liter: ",ID));
mLayout[ID].addView(createNewEditText(ID));
ID++;
}
};
}
XML: (This LinearLayout is empty: no EditText, Buttons etc and is inside another LinearLayout)
(More code from other LinearLayouts)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.66"
android:orientation="horizontal"
android:id="#+id/linearLayout_expandir">
</LinearLayout>
(More code from other LinearLayouts)
Thank you for your time!
One question: you only have 1 LinearLayout, why do you create an array of LinearLayout while you're not adding another LinearLayout to the LinearLayout?
The error probably occurred when the ID become 1, mLayout[1] has not been initialized and you're trying to add another view to it.
LinearLayout expandir = (LinearLayout) findViewById(R.id.linearLayout_expandir);
in the onClick() method:
public void onClick(View v) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.addView(createNewTextView("Contain: ", ID));
linearLayout.addView(createNewEditText(ID));
linearLayout.addView(createNewTextView("Nº Liter: ",ID));
linearLayout.addView(createNewEditText(ID));
expandir.addView(linearLayout);
ID++;
}
I've created a solution for you. This activity has a button that will generate layouts for you. I use an arraylist instead of an array but the idea is the same.
This is a picture of many nested layouts that have been created using this demo.
Once you get this code in your project, you will just have to add the TextView/Edit Text code that you mentioned. Let me know if you have any questions. :)
public class LinearLayoutActivity extends Activity {
/*This linear layout is the first container*/
LinearLayout outerMostLayout;
/*This array holds the linear layouts that you will create dynamically*/
List<LinearLayout> subLayouts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_linear_layout);
// Initialize your views
outerMostLayout = (LinearLayout) findViewById(R.id.container_layout);
subLayouts = new ArrayList<LinearLayout>();
Button button = (Button) findViewById(R.id.button);
// Set the button onclick
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get a reference to the container layout
LinearLayout container = outerMostLayout;
if (!subLayouts.isEmpty()) {
// Check to see if we have created any yet new containers yet
//-- If we have, then use the newest container
container = subLayouts.get(subLayouts.size() - 1);
}
// Initialize the new layout with padding to show the change
LinearLayout linearLayout = new LinearLayout(LinearLayoutActivity.this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(linearLayoutParams);
linearLayout.setPadding(16, 16, 16, 16);
// Add textview with linear layout name
TextView textView1 = new TextView(LinearLayoutActivity.this);
textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
textView1.setText("Linear Layout: " + (subLayouts.size() + 1));
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
linearLayout.addView(textView1);
// Add the layout to the array
subLayouts.add(linearLayout);
// Set the color of the new layout so that we can see the change
int size = subLayouts.size();
if (size % 2 == 0) {
// Every even layout will be blue
linearLayout.setBackgroundColor(getResources().getColor(R.color.blue));
} else {
// every odd layout will be red
linearLayout.setBackgroundColor(getResources().getColor(R.color.red));
}
// Finally, add the linear layout to the container layout
container.addView(linearLayout);
}
});
}
}
Here is the Layout 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"
android:background="#color/red"
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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"/>
<LinearLayout
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
</LinearLayout>
</LinearLayout>
How can i set the same image resource for a series of imagebutton using a for loop ?
ImageButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14,
b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27,
b28, b29, b30;
public void setresource() {
for (int i = 0 ; i <= 15; i++){
b[i].setImageResource(R.drawable.playzz);
}
}
The above code give error on b[i]
The type of the expression must be an array type but it resolved to int
Try the below. You have not initialized ImageButton
ImageButton b[];
In your onnCreate(param)
b = new ImageButton[15];
for (int i = 0 ; i <15; i++){
b[i] = new ImageButton(ActiivtyName.this);
b[i].setImageResource(R.drawable.playzz);
}
Also remember to add the button to you root view of the layout.
Example:
You can also set the layout programatically. You can use use linear layout or relative layout set the layout parameters. Add the Imagebuttons to the layout and set the content to the activity.
Modify the below according to your requirements.
activity_main.xml
<?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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll"
tools:context=".MainActivity" >
</LinearLayout>
</ScrollView>
MainActivity.java
public class MainActivity extends Activity {
ImageButton b[];
LinearLayout ll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.ll);// initialize linearlayout
setresource();
}
public void setresource()
{
b = new ImageButton[15];
for (int i = 0 ; i < 15; i++){
b[i]= new ImageButton(MainActivity.this); // initilize
b[i].setMaxWidth(40); // set the maxwidth
b[i].setImageResource(R.drawable.ic_launcher); // set background image
ll.addView(b[i]); // add the imagebutton to the linearlayout
}
}
}
android ImageView is not bringing to front in RelativeLayout
Tried to call bringtofront() didn't work
tried setting visibility to true didn't work
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is /res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spellingLevel1Layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<RelativeLayout
android:id="#+id/canvas_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/magnetboard" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="480dp"
android:layout_marginTop="600dp"
android:adjustViewBounds="true" />
</RelativeLayout>
</LinearLayout>
Java Code
public class spellingLevel1 extends Activity {
rel1 = (RelativeLayout) findViewById(R.id.canvas_container);
mImageView1 = (ImageView) findViewById(R.id.imageView1);
image1();
}
public void randomNumber() {
Random rando = new Random();
currentLetter = myImageList[rando.nextInt(myImageList.length)];
}
public void image1(){
//randomNumber();
mImageView1 = (ImageView) findViewById(R.id.imageView1);
mImageView1.setBackgroundResource(R.drawable.spelling_);
mImageView1.bringToFront();
mImageView1.requestLayout();
}
UPDATED CODE
rel1 = (RelativeLayout) findViewById(R.id.canvas_container);
mImageView1 = (ImageView) findViewById(R.id.imageView1);
image1();
}
public void randomNumber() {
Random rando = new Random();
currentLetter = myImageList[rando.nextInt(myImageList.length)];
}
public void image1(){
//randomNumber();
mImageView1 = (ImageView) findViewById(R.id.imageView1);
mImageView1.setImageResource(R.drawable.spelling_); //updated here to setImageResource
mImageView1.bringToFront();
Still does not show
its not the full code but it should be everything to help you see what is included in here
You should define the image source of the ImageView.
because it's size is set to wrap_content and it has no content, the size stays 0.
I am a android beginner, I have added images dynamically inside the linear layout, which will scroll from right to left. The problem is that the images are moving / scrolling properly but when I click on it the on-click listener is not called.
Actually when moving the images the image button is moving but the onclick position is not changed according to the image scrolling.
public class ImageLayoutsActivity extends Activity {
int ImageInt, fromXDelta, toXDelta;
int PosInt, myHarizantalLayoutInt, aDisplayInt, aDisplayDiv = 0;
AnimationSet myAnimation = new AnimationSet(true);
LinearLayout myHarizantalLayout;
HorizontalScrollView myHorizontalScroll;
View myView;
Intent myIntent;
private Button clickedButton = null;
public int currentimageindex = 0;
TranslateAnimation myTranslateAnimation = null;
private String[] imgArr = { "icn01", "icn02" };
private String[] URLArray = { "http://www.google.co.in/",
"http://in.yahoo.com/?p=us" };
LinearLayout.LayoutParams Parems;
Display aDisplay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View aView = LayoutInflater.from(GroupActivity.myGroup).inflate(
R.layout.horizantal, null);
setContentView(aView);
GroupActivity.myGroup.setTitle("---CII---");
aDisplay = getWindowManager().getDefaultDisplay();
aDisplayInt = aDisplay.getWidth();
aDisplayDiv = aDisplayInt / 5;
Log.i("value##########################", String.valueOf(aDisplayDiv));
Log.i("aDisplayInt##########################",
String.valueOf(aDisplayInt));
// define xml layout here
myHarizantalLayout = (LinearLayout) findViewById(R.id.horiztonal_outer_layout_id);
myHorizontalScroll = (HorizontalScrollView) findViewById(R.id.horiztonal_scrollview_id);
// Button aBtnOne = (Button) findViewById(R.id.BtnOneId);
// Hide HorizantalLayout scroll bar
myHorizontalScroll.setHorizontalScrollBarEnabled(false);
myHorizontalScroll.isSmoothScrollingEnabled();
myHarizantalLayout.measure(aDisplay.getWidth(), aDisplay.getHeight());
Log.v("EmailActivity#########", myHarizantalLayout.getMeasuredHeight()
+ ", " + myHarizantalLayout.getMeasuredWidth());
int aLayoutInt = myHarizantalLayout.getMeasuredWidth();
Log.i("aLayoutInt###########", String.valueOf(aLayoutInt));
// Add images in for loop
for (int i = 0; i < imgArr.length; i++) {
// int aVal=myHarizantalLayout.getChildCount();
Log.i("ImageInt############################", "=====Inside the loop======");
// create button instance
final Button aImgBtn = new Button(this);
// myButton.setOnClickListener(null);
// add background image resource files
ImageInt = getResources().getIdentifier(imgArr[i], "drawable",
getPackageName());
Log.i("ImageInt############################", "ImageInt");
// add integer image values to drawable control
Drawable aDrawable = this.getResources().getDrawable(ImageInt);
Log.i("aDrawable$$$$$$$$$$$$$$$$$$$$$$$$$", "aDrawable");
// add drawable file to button instance
aImgBtn.setBackgroundDrawable(aDrawable);
aImgBtn.measure(aDisplay.getHeight(), aDisplay.getWidth());
Log.i("aButton#############################", "aButton");
Parems = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Parems.setMargins(10, 0, 5, 0);
Log.i("Parems%%%%%%%%%%%%%%%%%%%%%%%%%%", "Parems");
// int aParemIn = Parems.width;
// Log.i("aparemIn$$$$$$$$$$$$", String.valueOf(aParemIn));
myHarizantalLayout.measure(aDisplay.getHeight(),
aDisplay.getWidth());
int myHarizantalLayoutInt = myHarizantalLayout.getMeasuredWidth();
Log.i("myHarizantalLayoutInt$$$$$$$$$$$$",
String.valueOf(myHarizantalLayoutInt));
myTranslateAnimation = new TranslateAnimation(aDisplayInt - 300,
-myHarizantalLayoutInt - aDisplayDiv, 0, 0);
myTranslateAnimation.setDuration(20000);
myTranslateAnimation.setRepeatCount(-1);
myTranslateAnimation.setRepeatMode(1);
myAnimation.addAnimation(myTranslateAnimation);
Log.i("myAnimation###########################", "myAnimation");
aImgBtn.setLayoutParams(Parems);
myHarizantalLayout.addView(aImgBtn);
Log.i("myHarizantalLayout&&&&&&&&&&&&&&&&&&&&&&&&&",
"myHarizantalLayout");
// add animation to HarizantalLayout
myHarizantalLayout.startAnimation(myTranslateAnimation);
// Call webview based on image button click event
aImgBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.i("view$$$$$$$$$$$$#############", "---btn clicked -----");
int aVal = myHarizantalLayout.indexOfChild(view);
Log.i("indexOfChild*************************",
"indexOfChild");
if (view == aImgBtn) {
Log.i("aButton%%%%%%%%%%%%%%%%%%%%%%%%", "aButton");
aImgBtn.setId(aVal);
String aUrlStr = URLArray[aVal];
Log.i("aUrlStr$$$$$$$$$$$$#############", aUrlStr);
}
// Log.i("aUrlStr$$$$$$$$$$$$#############", aUrlStr);
// Pass values to webview activity
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="bottom" android:background="#00f">
<LinearLayout android:layout_below="#+id/RelativeLayout"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="horizontal" android:gravity="bottom">
<ImageView android:id="#+id/barImageId"
android:layout_width="150dp" android:layout_height="58dp"
android:background="#drawable/cii" android:layout_alignParentRight="true" />
<HorizontalScrollView android:layout_width="fill_parent"
android:layout_height="58dp" android:id="#+id/horiztonal_scrollview_id"
android:fadingEdge="none" android:background="#000" >
<LinearLayout android:id="#+id/horiztonal_outer_layout_id"
android:fadingEdge="none" android:layout_height="fill_parent" android:gravity="center_vertical"
android:layout_width="fill_parent" android:background="#f00">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</RelativeLayout>
Try to Use Pager instead of HorizontalScrollView,
This link may be helpful https://github.com/nostra13/Android-Universal-Image-Loader