How do I add an ImageView to the root layout? - java

I am following this tutorial into making an app for Android and ran into a problem. Disclaimer: I know next to nothing about Java or Eclipse, so bear with me.
I created a bitmap, which I put into an ImageView(?), and now the tutorial says to add the ImageView to the root_layout, but to be fair, I have no idea what the root_layout is (I Googled some, but couldn't find the right answer). Also, Eclipse gives me the 'layoutroot cannot be resolved or is not a field'-error, which I do not know how to solve. My question then is, how do I get the image to display on the screen? Thanks in advance :-)
Here is my (full) code:
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class ShowImage extends ActionBarActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// shows the activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
try {
// load large image from resources
Bitmap game_image = BitmapFactory.decodeResource(this.getResources(), R.drawable.sample_0);
// create cropped image from loaded image
Bitmap cropped = Bitmap.createBitmap(game_image, 0, 0, 100, 100);
// no longer need larger image
game_image.recycle();
// create ImageView to display image
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(cropped);
// add ImageView to root layout
LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
root.addView(imageView);
}
// catch comes here
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// shows GamePlay-activity after three seconds
Intent intent = new Intent(ShowImage.this, GamePlay.class);
ShowImage.this.startActivity(intent);
ShowImage.this.finish();
}
}, 3000);
}
}
Added .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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="nl.mprog.projects.nPuzzle10206353.ShowImage" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wait three seconds..." />
</RelativeLayout>

root_layout is basically the existing layout in your xml in which you want to add newly created View.
Assign id root_layout to the RelativeLayout in your xml file.
OR
Keep a new Layout inside it with root_layout id.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_layout"
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"
tools:context="nl.mprog.projects.nPuzzle10206353.ShowImage" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wait three seconds..." />
</RelativeLayout>
So now when you use this in Activity:
RelativeLayout root = (RelativeLayout)this.findViewById(R.id.root_layout);
root.addView(imageView);
imageView would be added to that RelativeLayout with id root_layout

add the imageView to your xml:
<ImageView android:id="#+id/mImageView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:contentDescription="solecito"
android:layout_weight = "1"
android:layout_gravity="center"
/>
then add it on you onCreate Method
ImageView im = (ImageView)findViewById(R.id.mImageView);
after you can add the image
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
im.setImageBitmap(bitmap);

package com.tommymacwilliam.androidwalkthroughapp3;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ImageView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class AndroidWalkthroughApp3 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// load large image from resources
Bitmap background = BitmapFactory.decodeResource(this.getResources(), R.drawable.puzzle_0);
// create cropped image from loaded image
Bitmap cropped = Bitmap.createBitmap(background, 0, 0, 230, 230);
// no longer need larger image
background.recycle();
// create ImageView to display image
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(cropped);
// add ImageView to root layout
LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);
root.addView(imageView);
int screenWidth = this.getResources().getDisplayMetrics().widthPixels;
Toast.makeText(this, String.valueOf(screenWidth), Toast.LENGTH_LONG).show();
}
catch (OutOfMemoryError e) {
// uh oh.
}
}
}

Related

How to implement Asynctask to load images in ArrayAdapter

I'm working on a course list app which loads each course title together with the course image in a listview through ArrayAdapter, I want to implement asynctask for loading of images in between listview and ArrayAdapter because the listview is lagging while scrolling, Please Help me.
MainActivity.java
package com.emmakade.okt;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
protected List<Course> data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = DataProvider.getData();
ArrayAdapter<Course> courseArrayAdapter =
new CourseArrayAdapter(this, 0, data);
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(courseArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Course course = data.get(position);
displayDetail(course);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DETAIL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
String msg = data.getStringExtra("resultMessage");
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
}
class CourseArrayAdapter extends ArrayAdapter<Course>{
Context context;
List<Course> objects;
public CourseArrayAdapter(Context context, int resource, List<Course> objects) {
super(context, resource, objects);
this.context = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Course course = objects.get(position);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.course_item, null);
TextView tv = (TextView) view.findViewById(R.id.tvTitle);
tv.setText(course.getTitle());
ImageView iv = (ImageView) view.findViewById(R.id.imageCourse);
int res = context.getResources().getIdentifier(
"image_" + course.getCourseNumber(), "drawable",
context.getPackageName()
);
iv.setImageResource(res);
return view;
}
}
}
activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageLogo"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:src="#drawable/academy"/>
<TextView
android:id="#+id/txtOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/course_catalog"
android:layout_alignBottom="#+id/imageLogo"
android:layout_toEndOf="#+id/imageLogo"
android:layout_marginStart="20dp"
android:layout_marginBottom="15dp"
android:textSize="28sp" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"
android:layout_below="#+id/imageLogo"
android:layout_marginTop="10dp"
android:layout_alignParentStart="true" />
</RelativeLayout>
course_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/imageCourse" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvTitle"
android:layout_toEndOf="#+id/imageCourse"
android:layout_marginStart="10dp"
android:textSize="18sp"/>
</RelativeLayout>
enter image description here
I recommend you to use Glide library for asynchronous image loading, caching and displaying.
Add Dependency
implementation 'com.github.bumptech.glide:glide:4.5.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.5.0'
Use like this in adapter
Glide.with(this).load("url").into(imageView);
ImageView iv = (ImageView) view.findViewById(R.id.imageCourse);
int res = context.getResources().getIdentifier(
"image_" + course.getCourseNumber(), "drawable",
context.getPackageName()
);
Glide.with(this).load(res).into(iv);
You can use handler because asynctask will work on another thread but you cant update ui from another thread instead of main thread. Also consider to use glide, picasso like libraries. These libraries caches images efficiently and works with more performence.
There is an example with Handler.
Handler handler = new Handler();
handler.post(() -> {
profilephoto.setImageBitmap(pp);
});

making an image exactly circular without borders

I want a circular image for my Profile activity. I have already tried these answers but it does n't work in my case.
How to create a circular ImageView in Android?
How to make an ImageView with rounded corners?
How to make an image fit into a circular frame in android
How to Make an ImageView in Circular Shape?
It's not a duplicate question,using all these methods , Here is what i get :-
Problem : image is not exactly circular.
here is my Profile.java code:-
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by kundan on 6/4/2015.
*/
public class Profile extends ActionBarActivity {
TextView username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
username= (TextView) findViewById(R.id.txt);
String recievedusername=getIntent().getExtras().getString("toname");
username.setText(recievedusername);
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.mipmap.gomez);
Bitmap resized= Bitmap.createScaledBitmap(bm,200,200,true);
Bitmap conv_bm=getCircleBitmap(resized,100);
// set circle bitmap
ImageView mImage = (ImageView) findViewById(R.id.profile_image);
mImage.setImageBitmap(conv_bm);
// TODO Auto-generated method stub
}
private Bitmap getCircleBitmap(Bitmap bitmap , int pixels) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(),bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(100, 100, 100, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
bitmap.recycle();
return output;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_apploud, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_addnew) {
Intent i;
i=new Intent(Profile.this,ApplaudSomeone.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Needed portion of my profile.xml is :-
<?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="wrap_content"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ff17a088"
android:weightSum="1"
android:paddingTop="5dp"
android:gravity="center">
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/profile_image"
android:contentDescription="#string/img"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:background="#drawable/img"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/txt2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="suman"
android:id="#+id/txt"
android:textSize="25sp"
android:padding="5dp"
android:layout_gravity="center_horizontal"
android:textColor="#fffff9"
android:layout_below="#+id/profile_image"
android:layout_centerHorizontal="true" />
code of img.xml is:-
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:useLevel="false"
>
<stroke android:width="5dp"
android:color="#ffffff"/>
</shape>
</item>
</layer-list>
Thanks in Advance!!
Yes, finally i solved this problem. If any of you are facing the same problem then use canvas.drawCircle(100, 100, 90, paint); instead of canvas.drawCircle(100, 100, 100, paint); this will definitely solve your problem.

How can i remove a imageView when i run my program on smaller devices

So i have this application, and i want to remove the logo when i run it on smaller devices sine its pressing the rest of the ui and making things look strange. It is the first application im making, so not sure how to get this done.
Here is my code for the main_activity:
package no.flammbaert.flammbaert;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener{
ImageButton btn_settings;
ImageButton btn_voksen;
ImageButton btn_barn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
#Override
public void onClick(View v) {
if(v.getId() == btn_voksen.getId()){
Intent i = new Intent(MainActivity.this, VoksenActivity.class);
startActivity(i);
}
if(v.getId() == btn_settings.getId()){
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
}
if(v.getId() == btn_barn.getId()){
Intent i = new Intent(MainActivity.this, BarnActivity.class);
startActivity(i);
}
}
public void Init(){
btn_settings = (ImageButton)findViewById(R.id.btn_settings);
btn_voksen = (ImageButton) findViewById(R.id.btn_voksen);
btn_barn = (ImageButton) findViewById(R.id.btn_barn);
btn_settings.setOnClickListener(this);
btn_voksen.setOnClickListener(this);
btn_barn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the xml file:
<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:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#drawable/bg_blue_sky">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayout"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/btn_settings">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_barn"
android:background="#drawable/knapp_1"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_voksen"
android:background="#drawable/knapp_2"
android:layout_below="#+id/btn_barn"
android:layout_alignLeft="#+id/btn_barn"
android:layout_alignStart="#+id/btn_barn"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/logo_flammbaert"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"/>
</RelativeLayout>
<ImageButton
android:id="#+id/btn_settings"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/gear"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:scaleType="fitXY"/>
</RelativeLayout>
Thanks for help.
I think you can check this way weather the app is running in a small or large screen using the below code snippet.
Configuration config = getResources().getConfiguration();
if((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_SMALL)
{
//small screen
// Here you can remove/invisible the image view by using
imageView.setVisible(View.GONE);
}
This can be a aproaching to what you need:
First obtain the size of the screen take a look to this post --> Get screen dimensions in pixels
Once you get the size, you have tos et your "small screen size", and make the Imageview "dissapear.
imageview = (ImageView)findViewByID(R.id.imageView)
imageview.setVisivility(View.GONE);
Take care because there are 2 ways to make "dissapear" a view:
View.GONE This view is invisible, and it doesn't take any space for
layout purposes. View.INVISIBLE This view is invisible, but it still
takes up space for layout purposes.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String screenSize = dm.widthPixels
+ " "
+ dm.heightPixels;
Now if you get the smaller device resolution simply use
setVisivility(View.GONE);
But I suggest to use
Supporting Different Screen Sizes

How can I add touch functionality to an ImageView in android?

I'm pretty new to android and was wondering how I could add some type of functionality to and ImageView is I press it. My current code in my activity java file is as follows
package com.example.crystalbabyheaven;
import android.app.Activity;
import android.util.Log;
import android.view.*;
import android.view.View.OnTouchListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ScrollView;
import android.widget.ImageView;
public class MainActivity extends Activity implements Runnable {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ScrollView sv = (ScrollView) findViewById(R.id.ScrollView);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
sv.scrollTo(0, 8000);
}
}, 100);
ImageView player = new ImageView(this);
player.setImageDrawable(getResources().getDrawable(R.drawable.crystalbaby));
player.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
sv.scrollTo(0, 5000);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ScrollView sv = (ScrollView) findViewById(R.id.ScrollView);
sv.scrollTo(300, 300);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
And here is my XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.crystalbabyheaven.MainActivity" >
<ScrollView
android:id = "#+id/ScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/bg" />
</ScrollView>
<ImageView
android:id="#+id/crystalBaby"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="bottom"
android:src="#drawable/crystalbaby" />
</FrameLayout>
I have a very large image that starts from a picture of the earth and scrolls upward through the atmosphere into space. I have another image view on top of this background. The first portion of my code in onCreate sets the scrollview view to the bottom of the image. What I want to do in this case is scroll approximately to the middle of the image when I press the image in the corner. I actually want something different, but I want to test this before anything. Is there something wrong in my code? I'm at a loss.
You're creating an ImageView player, but this is not the same as the imageview in your xml. Why not do: Imageview player = (ImageView)findViewById(R.id.imageview_player)
and in your xml, put android:id="#+id/imagview_player" inside the imageview.
Or if you must create the imageview programatically, then add it to your layout. You are not adding it to your layout anywhere in the code.

Methods in extended class are not working

I created a menu, where you can swipe up and down. I created this menu as another activity. Now, I need this menu to be added to on other activities.
Following is the code of my menu(SlidingDrawer)
Java
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class DropDownMenu extends Activity {
private TextView addInquiry, addEvent, additionalInfo, addToContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drop_down_menu);
//Intializing instance variables
addInquiry = (TextView)findViewById(R.id.menu_add_inquiry);
addEvent = (TextView)findViewById(R.id.menu_add_event);
additionalInfo = (TextView)findViewById(R.id.menu_additional_info);
addToContacts = (TextView)findViewById(R.id.menu_add_to_contacts);
//Register the Listeners
addInquiry.setOnClickListener(new AddInquiryEvent());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drop_down_menu, menu);
return true;
}
//Test Button
private class AddInquiryEvent implements OnClickListener
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(DropDownMenu.this,NewLead.class);
startActivity(intent);
}
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<SlidingDrawer
android:id="#+id/SlidingDrawer"
android:layout_width="wrap_content"
android:layout_height="250dip"
android:layout_alignParentBottom="true"
android:content="#+id/contentLayout"
android:handle="#+id/slideButton"
android:orientation="vertical" >
<Button
android:id="#+id/slideButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/bottom_bar" >
</Button>
<LinearLayout
android:id="#+id/contentLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dip"
android:background="#cbcbcc" >
<TextView
android:id="#+id/menu_add_inquiry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/add_inquiry"
android:textColor="#ffffff"
android:clickable="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</SlidingDrawer>
</RelativeLayout>
Following is the Code of the other activity
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/sales_inqury_main_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SalesInqury" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:text="#string/sales_inqury"
android:textSize="40sp" />
<include layout = "#layout/activity_drop_down_menu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Java
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class SalesInqury extends DropDownMenu {
private ImageView addNewSalesInqury;
private RelativeLayout salesInquryMainLayout;
private TextView testEditSales;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_inqury);
//Intializing instance variables
addNewSalesInqury = (ImageView)findViewById(R.id.add_new_sales_inqury_btn);
salesInquryMainLayout = (RelativeLayout)findViewById(R.id.sales_inqury_main_layout);
testEditSales = (TextView)findViewById(R.id.testWord);
}
}
But, there is an issue. Even thougn I can open the menu in this other activity, I can't click on it's Buttons (TextViews) and navigate to other activities. Why is this?
I think it's because after you've set a contentView in your DropDownMenu activity and bound the listener to the button, in SalesInquiry you set a different contentView. Although this includes the menu-layout, the Views are created anew, so there's no Listener bound to the button anymore.
A solution would either be to specify the menu callbacks in the layout xml via android:onClick="..." or by having a separate method in DropDownMenu that adds the Listener and that you call from your SalesInquiry class after setting the content view.
Example 1, specifying callback in XML
Add android:onClick="onMenuItemClicked" to menu item TextView
<TextView
android:id="#+id/menu_add_inquiry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="#string/add_inquiry"
android:textColor="#ffffff"
android:clickable="true"
android:onClick="onMenuItemClicked"
android:textAppearance="?android:attr/textAppearanceMedium"/>
Add this method to DropDownMenu class and remove the AddInquiryEvent class and the registering of the listeners.
public void onMenuItemClicked(View view) {
switch (view.getId()) {
case R.id.menu_add_inquiry:
Intent intent = new Intent(DropDownMenu.this,NewLead.class);
startActivity(intent);
break;
case R.id.menu_other:
// handle other menu item
break;
// ... and so on ...
default:;
}
}
Example 2, bind listeners in a separate method
In DropDownMenu move the registering of the Listeners to a separate method:
protected void registerListeners() {
//Register the Listeners
findViewById(R.id.menu_add_inquiry).setOnClickListener(new AddInquiryEvent());
}
Note, that you have to find the view again, as the one kept in the local variable is the wrong one, after SalesInquiry set it's content view.
Call the method in SalesInquiry after setting the content view.
setContentView(R.layout.activity_sales_inqury);
registerListeners();
I'm not sure. but can you please try with extending the DropDownMenu-Activity instead of Activity.
public class NewActivity extends DropDownMenu {
// override which you want to override
}
And make sure DropDownMenu in such a way that you can extends what you want to implements. Hope you have got my point.
Consistency Issue (Recommendation)
There is a HUGE misnomer in your class name, you should NOT call an Activity DropDownMenu.
This is confusing, you should instead call it DropDownActivity or something like that. Also do you really need to use an Activity? You do realize a View can still listen to the click of a button right? Not only an Activity can listen to button clicks. If you encapsulate all of this in a View and have a dedicated listener for that view, then you wouldn't have any need for another Activity.
Possible Solution
It's likely related to the activity/component you have registered to listen to the buttons is not correct. Validate your code so that you can at least get the correct response of the onClick.
The problem is that you are attaching the listener to addInquiry in the DropDownMenu:
//Register the Listeners
addInquiry.setOnClickListener(new AddInquiryEvent());
This listener is not attached to the TextView in the extended class, since the setContentView is called and layout is refreshed.
Possible solution, if you are not using the DropDownMenu activity on its own then simply (remove setContentView):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //in DropDownMenu
// setContentView(R.layout.activity_drop_down_menu);
...
...
Not the best solution but would work.
Update: Better Solution
(1) Let the subclass decide which layout to show. This layout must contain the menu (which is true in your case).
public class DropDownMenu extends Activity {
private TextView addInquiry, addEvent, additionalInfo, addToContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_setContentView();
//Intializing instance variables
addInquiry = (TextView)findViewById(R.id.menu_add_inquiry);
addEvent = (TextView)findViewById(R.id.menu_add_event);
additionalInfo = (TextView)findViewById(R.id.menu_additional_info);
addToContacts = (TextView)findViewById(R.id.menu_add_to_contacts);
//Register the Listeners
addInquiry.setOnClickListener(new AddInquiryEvent());
}
protected void _setContentView() {
setContentView(R.layout.activity_drop_down_menu);
}
...
...
}
#override the _setContentView method so that we do not set the view twice.
public class SalesInqury extends DropDownMenu {
...
...
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//Intializing instance variables
addNewSalesInqury = (ImageView)findViewById(R.id.add_new_sales_inqury_btn);
salesInquryMainLayout = (RelativeLayout)findViewById(R.id.sales_inqury_main_layout);
testEditSales = (TextView)findViewById(R.id.testWord);
}
#Override
protected void _setContentView() {
// need to make sure this layout contains the menu (otherwise NullPointerException may arise)
setContentView(R.layout.activity_sales_inqury);
}
}

Categories