Display images through array in Android Studio - java

I'm trying to re-rig a quiz app to instead of displaying text questions, will display images (Ishihara slides to be specific).
For reference, here's a screenshot of the original quiz app:
When a user selects the true or false buttons, a toast appears with the result. Straightforward, and the previous/next buttons cycle through the questions. The questions are being stored as such:
final QuestionAndAnswer[] mQandA = new QuestionAndAnswer[]{
/*1*/ new QuestionAndAnswer(R.string.question_northAmerica, true),
/*2*/ new QuestionAndAnswer(R.string.question_antarctica, false),
/*3*/ new QuestionAndAnswer(R.string.question_canada, false),
/*4*/ new QuestionAndAnswer(R.string.question_madagascar, true),
/*5*/ new QuestionAndAnswer(R.string.question_wonders, false)
};
I thought that pointing the new QuestionAndAnswer at R.drawable.imagename could accomplish this, but instead just displays the image's location as text.
And changing it to new ImageView(R.drawable.imagename, true) throws the error:
ImageView (android.content.Context, android.util.AttributeSet)in ImageView cannot be applied to (int,boolean)
I'm sorry, I'm still very new to Android but as you've probably put together by now, I'm a student and don't have a choice but to do this.

If you have something like this on layout xml
<RelativeLayout ...
...
<TextView android:id="#+id/text_view_id" ... />
...
</RelativeLayout>
You need to change it to
<RelativeLayout ...
...
<ImageView android:id="#+id/image_view_id" ... />
...
</RelativeLayout>
Then on your activity class, maybe you have something like below
TextView textView;
public void onCreate() {
textView = (TextView) findViewById(R.id.text_view_id);
....
textView.setText(mQandA[i].question)
}
Where mQandA[i].question is your question resource a.k.a R.string.question_northAmerica
Change it to
ImageView imageView;
public void onCreate() {
imageView = (ImageView) findViewById(R.id.image_view_id);
...
imageView.setImageResource(mQandA[i].question)
}
Where mQandA[i].question is your image resource a.k.a R.drawable.imagename
EDIT 1
change every appearance of
textView.setText(mQandA[i].question)
with
imageView.setImageResource(mQandA[i].question)
counterpart

Related

I need help on android Toast view as icon on error

My activity is a Video Player Activity and its working fine, On some Videos it must throw a message (handleHardwareAccelerationError) if the video is not supported or high quality.
It shows as Toast with message fine.
Now I would like to change this Toast message to show a picture or small icon instead, is this possible? Here is my code for handleHardwareAccelerationError, Thanks in advance.
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
Toast.makeText(this, R.string.hardware_acceleration_error, Toast.LENGTH_LONG).show();
}
what I have tried is this but didnt show anything.
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
mError = (ImageView) popupView.findViewById(R.id.errornew);
mError.setVisibility(View.VISIBLE);
}
and here is myinforbar.xml
<LinearLayout android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="21dp" android:layout_marginLeft="0.0dip" android:layout_marginTop="5.0dip"
android:background="#drawable/button5_background">
<ImageView
android:id="#+id/errornew"
android:src="#drawable/everyone_icon_nearby_cur"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:visibility="invisible"/>
</LinearLayout>
EDITED:
The original activity is long and it can be found here rather then pasting the whole activity you can see it here VideoPlayerActivity
( private void handleHardwareAccelerationError)
New Update...
This is without the message (onHardwareError) applied, I want to see icon inside this bottom little box that popup when video playing (infobar) instead of Toast message.
Toast is farily limited, you cannot show icons.
Edit: Gunjav Dave says it's possible, so it's approach worth a try.
Anyway this free library: SuperToast
can make what you need.
If you prefer to stick to Google's standards you can use, instead, the Snackbars, that don't allow, as far as I know, to put an icon, but can anyway be associated with an action/button, and they are standard.
I can't understand what you try to do with popupView, if you want to use a PopupWindow you have to use a completely different syntax. This Balloon Popup library of mine helps you to make a popup attached to a View, using a PopupWindow, you can also inflate into it a layout, or use it as an example on how to make a PopupWindow.
Edit:
You are inflating a layout inside a view, but this doesn't show the view. Instead, you should use a PopupWindow, and inflate inside it a layout.
This is an example taken from my BalloonPopup library:
// ....
hostedView = ((LayoutInflater) ctx.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(layoutRes, null);
textView = (TextView) hostedView.findViewById(R.id.text_view);
textView.setText(text);
// ....
popupWindow = new PopupWindow(hostedView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
In other words, you should be able to do something like
PopupWindow popupWindow = new popupWindow(mError, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
in your code to show the popup window.
These are the essential points of the code, then you can reposition the popup, and eventually keep track of it to edit and re-show it instead of always creating from scratch. Please consider, anyway, to use BalloonPopup library, that does what you need, without getting crazy with animations, display times, window's permanence and positioning. You can just inflate into it your layout, for example with an icon and a text, and make it appear exactly on the center of another View, that can be your (already present) media player.
More edit:
Another very simple solution.
To get it simple, create a RelativeLayout, that hosts all your video player, and then create a simple ImageView in the center of it. Set its visibility to GONE when hidden and to VISIBLE when the error must be shown. Subsequently, you can use a timer or a touchListener to close it making it GONE again.
Try this
private void handleHardwareAccelerationError() {
mHardwareAccelerationError = true;
if (mSwitchingView)
return;
final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
PopupWindow pw = new PopupWindow(popupView , 300, 400, true);
pw.showAtLocation(popupView , Gravity.CENTER, 0, 0);
mError = (ImageView) popupView.findViewById(R.id.errornew);
mError.setVisibility(View.VISIBLE);
}
XML Name or Layout Name would be
<LinearLayout xmlns:androidclass="http://schemas.android.com/apk/res/android"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button5_background">
<ImageView
android:id="#+id/errornew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
</LinearLayout>
Put This in Class:
LayoutInflater inflater = LayoutInflater.from(this);
View layout= inflater.inflate(R.layout.myinforbar, null);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();

Android ImageButton swap resource leaves 'residue'

I have 2 Images:
IMG_1:
IMG_1_PRESSED:
I display IMG_1 by default, but when I click on it, the image should change to IMG_1_PRESSED.
Here's a code snippet of the button itself, where be is an enum containing the correct drawables:
ImageButton ib = new ImageButton(this.context);
ib.setImageResource(be.getDrawable());
ib.setScaleType(ImageButton.ScaleType.CENTER_INSIDE);
ib.setBackgroundColor(Color.TRANSPARENT);
ib.setPadding(0, 0, 0, 0);
ib.setAdjustViewBounds(true);
ib.setMaxWidth(width);
ib.setMaxHeight(height);
setStrengthListener(ib, be);
And here is the setStrengthListener method:
private void setStrengthListener(final ImageButton ib, final ButtonEnum be){
ib.setOnTouchListener(new View.OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
ib.setImageResource(be.getDrawablePressed());
return true;
case MotionEvent.ACTION_UP:
ib.setImageResource(be.getDrawable());
return true;
}
return false;
}
});
}
Now both images are 480x240 and width and height are set to device's width/3 and device's width/6 respectively (I want to display 3 images, hence the /3).
Here's the problem, if the button is pressed, I get this:
There's this little line under the pressed button... I've tried a lot to fix this but somehow that little line has made itself my greatest enemy today.
As an extra effort: the line doesn't show anymore if I set the original resource to IMG_1_PRESSED:
ImageButton ib = new ImageButton(this.context);
ib.setImageResource(be.getDrawablePressed());
ib.setScaleType(ImageButton.ScaleType.CENTER_INSIDE);
ib.setBackgroundColor(Color.TRANSPARENT);
ib.setPadding(0, 0, 0, 0);
....etc
But obviously I don't want to start with a pressed button.
So dear Android experts, what am I doing wrong here?
This is the simplest solution as i know,
Try this
create Xml inside your Drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/btn_pressed_img"android:state_pressed="true" />
<item android:drawable="#drawable/btn_normal_image" />
</selector>
Then add this drawable file as background to your View
Example :
<ImageView
android:id="#+id/enter_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxHeight="100dip"
android:maxWidth="100dip"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:background="#drawable/enter_btn" />
or in Java code
yourView.setImageResource(R.drawable.*drawablefile*);
You can use ImageButton also but ImageView would look better than ImageButton since it doesn't have button borders.
So after a hell of a lot of trial and error, I managed to get that grey line away. In the end it was very simple really, though I'm not completely sure why this fixed it:
The main layout:
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setGravity(Gravity.TOP);
The view creation (layout for imageview is unchanged):
ImageView iv = tbb.getTopBarButton(ButtonEnum.IMG_1);
LinearLayout iViewLayout = new LinearLayout(this);
iViewLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
iViewLayout.setOrientation(LinearLayout.HORIZONTAL);
iViewLayout.addView(iv);
ll.addView(iViewLayout);
Adding a separate layout per imageview seemed to remove the grey line. Would love to know WHY this works though, but for future reference, at least I hope to help others.

Click listview item and display image

im trying to create a listview where if you press an item on that list, it displays an image in fullscreen. I have about 10 different items in the list and I want to display different images for each item.
I used this tutorial: http://www.androidhive.info/2011/10/android-listview-tutorial/
But instead of showing the name of my string item, i want it to show an image. How do i fix this?
I have been trying to check other questions, but they have been kinda hard to follow since im new to this.
First of all you need to have images in your drawable folder for all different items(in list view)
Change the single_list_item.xml to
single_list_item_view.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">
<ImageView android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
change your SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
ImageView productimage = (ImageView) findViewById(R.id.image);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
switch(product){
case "item1":
productimage.setImageDrawable(R.drawable.image1);
break;
case "item2":
productimage.setImageDrawable(R.drawable.image2);
break;
case "item3":
productimage.setImageDrawable(R.drawable.image3);
break;
.
.
.
.
.
//upto all 10 images
}
}
}
You should be able to do this with only a few changes to the tutorial code.
First, in single_list_item_view.xml, you'll need to use an ImageView instead of a TextView, since you want to show an image. You can find documentation for image views, including what attributes they support, on the Android developer site.
Second, you'll need to change the line that looks up the TextView to find your new ImageView instead. This will only require changing the following line:
TextView txtProduct = (TextView) findViewById(R.id.product_label);
to:
// Assuming you gave your ImageView the id "product_image" in single_list_item_view.xml
ImageView productImage = (ImageView) findViewById(R.id.product_image);
You'll need to add the images that you want to show into your project. The simplest place for these to go is in the res/drawable folder. The name of the image files will determine their "ids". For example, if you have res/drawable/photoshop.png, you can refer to it with the id R.drawable.photoshop.
Next you need to figure out which image to show in SingleListItem. The key part of how clicking on an item in the list shows something else is in SingleListItem:
Intent i = getIntent();
String product = i.getStringExtra("product");
Correspondingly, in AndroidListViewActivity:
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
i.putExtra("product", product);
startActivity(i);
The Intent is how you send information from the list activity to the activity that shows the item. In this case, the information being sent is which item to show. You have a few options about how to do this part. One simple way is just to inspect the product string and choose the appropriate drawable:
int imageId = -1;
if (product.equals("Adobe After Effects")) {
imageId = R.drawable.after_effects;
} else if (product.equals("Adobe Bridge")) {
imageId = R.drawable.bridge;
} else if ...
... // All your other cases
}
This approach obviously doesn't scale very well, but it will work okay for your simple example. Another possible approach would be to pass the image id in the Intent, rather than the product name, for example:
// In AndroidListViewActivity:
i.putExtra("product", R.drawable.after_effects);
// In SingleListItem:
int imageId = i.getIntExtra("product", -1);
// -1 in the call above is the value to return if "product" is not in the Intent
The final thing you need to do is set the Drawable for the ImageView you found earlier:
// Make sure to check that the id is valid before using it
if (imageId != -1) {
Drawable d = getResources().getDrawable(imageId);
productImage.setDrawable(d);
}
getResources() fetches the Resources object for you application. You can use the Resources object to look up things like strings and drawables you've defined in your res folder. The tutorial you're following also uses it to look up an array of strings in the res folder. Again, you can see everything Resources supports on the Android developer site.
Instead of showing the item/text in SingleListItem class you could use the passed item to check which image should be displayed in an imageview. Something like that:
public class SingleListItem extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
// TextView txtProduct = (TextView) findViewById(R.id.product_label);
ImageView image = (ImageView) findViewById(R.id.someImage);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
if (product.equals("item1")) {
image.setDrawableResource(R.drawable.YOURIMAGE);
} else if (product.equals("item2"))
image.setDrawableResource(R.drawable.ANOTHERIMAGE);
}
}

Making a button that creates an object and displays it when clicked

I have a program that handles song objects with some fields and playlist objects that are arrays of the songs. I have a perfectly functioning java programming that does what I need it to do but I'm trying to convert it into an Android app and it's making me want to throw my computer out the window. I don't really know XML but I've gotten the basics such as creating buttons etc.
I have a button in the layout file that I implemented as follows:
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/Button"
android:onClick="newPlaylist"/>
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1" />
In my main file I have:
public void newPlaylist(View view){
Playlist list1 = new Playlist("First Playlist");
TextView first = (TextView) findViewById(R.id.textView1);
first.setText(list1.getName());
}
Edit: I was able to add a little to the newPlaylist method. Now when I click the button it displays the name of the playlist, but I still want to edit it and be able to have multiple playlists on the screen to manipulate.
All I want to do is display the playlist name as either a text or label that is clickable so that the name can be changed and I can move on from here.
The Android documentation on the button component might help you with your problem.
I assume that your Playlist class looks something like this
public class Playlist {
private String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
If it does, then your method for handling the button click should look like this.
public void newPlaylist(View view) {
Playlist playlist = new Playlist("My First Playlist!"); // Create our playlist object
// Since button is the only component that uses 'newPlaylist' as a click listener, the view will always be the button
Button button = (Button) view; // We cast the view to button
button.setText(playlist.getName()); // This edits the button text, might want to create a TextView for this
}

Creating methods and updating strings

I am relatively new to Android development but I do have a pretty good understanding of Java and xml etc. so excuse me if this is an easy question and I just can't put two and two together.
Anyway, I am trying to have a user input a few characters into an EditText field. When they press a Button, it will call a method that will output a String. I then want this String to be displayed on the same activity as the EditText field and Button.
How do I go about taking the String variable that is the result of the method and putting into a String in the strings.xml file?
See this question. I don't think that is possible, what you probably want to do is store what the user enters in SharedPreferences.
EDIT:
To take the string variable and display it on the screen you would want to add a TextView to your layout:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text=""/>
Then in code you will add a listener to your button to listen for click events, and have a reference to the TextView in your class:
Fields in class:
TextView tv;
Button myButton;
EditText et;
onCreate():
tv = (TextView)findViewById(R.id.textview);
myButton = (Button)findViewById(R.id.button);
et = (EditText)findViewById(R.id.edittext);
//Now set the onclick listener:
myButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(args....)
{
String txt = et.getText().toString();
tv.setText(txt);
}
});
Also check out this tutorial.

Categories

Resources