我对Android开发相对较新,我的背景更多是php,html5等。我已经学习过,继续学习教程,正在研究我的第一个应用程序,我实际上已经按照我希望的方式进行,保存一个特定的项目。我希望你能帮助我,对某些人来说,这可能是一个简单的回应。但是,我已经尝试过,并且无法在没有错误的情况下解决问题。
基本上,应用程序使用ViewPager,并将SlidingImageActivity作为类,因此当以完整大小加载图像(从缩略图中单击)时,可以在屏幕之间刷新图像。
我有动作栏项目,而不是在溢出栏中显示,我创建了图像按钮,并放在下面的xml中,用于viewpager。它是文件 - fullimageslider.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/grid_back_color"
tools:ignore="RtlHardcoded" >
<android.support.v4.view.ViewPager
android:id="@+id/image_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/menu_zoom"
android:background="@color/grid_back_color" >
</android.support.v4.view.ViewPager>
<ImageButton
android:id="@+id/menu_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="@color/grid_back_color"
android:padding="10dp"
android:src="@drawable/save"
android:title="@string/menu_save" />
<ImageButton
android:id="@+id/menu_setaswallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="@color/grid_back_color"
android:padding="10dp"
android:src="@drawable/set"
android:title="@string/menu_setaswallpaper" />
<ImageButton
android:id="@+id/menu_zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="43dp"
android:layout_toRightOf="@+id/menu_share"
android:background="@color/grid_back_color"
android:padding="10dp"
android:src="@drawable/zoom"
android:title="@string/menu_zoom" />
<ImageButton
android:id="@+id/menu_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="32dp"
android:layout_toRightOf="@+id/menu_setaswallpaper"
android:background="@color/grid_back_color"
android:padding="10dp"
android:src="@drawable/share"
android:title="@string/menu_share" />
</RelativeLayout>
我已经在viewpager下方添加了按钮。因此,当屏幕滑动时,它们仍然位于布局的底部。
我的问题是,让按钮在SlideImageActivity类中运行。我不确定在哪里将溢出菜单任务更改为按钮任务。我从菜单中删除了我创建的项目按钮。并将它们改为上述内容。
以下是当前的SlideImageActivity类。
public class SlideImageActivity extends SherlockActivity
implements sensorEventListener {
int position;
String[] mAllImages,mAllImageCatName;
public DatabaseHandler db;
ImageView vp_imageview;
ViewPager viewpager;
int TOTAL_IMAGE;
private SensorManager sensorManager;
private boolean checkImage = false;
private long lastUpdate;
Handler handler;
Runnable Update;
boolean Play_Flag=false;
private Menu menu;
private DatabaseManager dbManager;
String Image_catName,Image_Url;
Bitmap bgr;
DisplayImageOptions options;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimageslider);
db = new DatabaseHandler(this);
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
setTitle(Constant.CATEGORY_TITLE);
// Look up the AdView as a resource and load a request.
Intent i=getIntent();
position=i.getIntExtra("POSITION_ID", 0);
mAllImages=i.getStringArrayExtra("IMAGE_ARRAY");
mAllImageCatName=i.getStringArrayExtra("IMAGE_CATNAME");
TOTAL_IMAGE=mAllImages.length-1;
viewpager=(ViewPager)findViewById(R.id.image_slider);
handler=new Handler();
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(position);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int position) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int position) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.photo_menu, menu);
this.menu = menu;
//for when 1st item of view pager is favorite mode
FirstFav();
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case android.R.id.home:
onBackPressed();
return true;
case R.id.menu_back:
position=viewpager.getCurrentItem();
position--;
if (position < 0) {
position = 0;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_next:
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_play:
if(Play_Flag)
{
handler.removeCallbacks(Update);
menuItem.setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
ShowMenu();
}
else
{
/*
* when Play_Flag false then Play
* but when image is last not start auto play
* now hide all menu when auto play start
*/
if(viewpager.getCurrentItem()==TOTAL_IMAGE)
{
Toast.LENGTH_SHORT).show();
}
else
{
AutoPlay();
menuItem.setIcon(getResources().getDrawable(R.drawable.stop));
Play_Flag=true;
HideMenu();
}
}
return true;
case R.id.menu_fav:
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
AddtoFav(position);//if size is zero i.e means that record not in database show
add to favorite
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
RemoveFav(position);
}
}
return true;
case R.id.menu_overflow:
//just override click
return true;
case R.id.menu_share:
position=viewpager.getCurrentItem();
(new ShareTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_save:
position=viewpager.getCurrentItem();
(new SaveTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_setaswallaper:
position=viewpager.getCurrentItem();
Intent intwall=new intent(getApplicationContext(), SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
case R.id.menu_zoom:
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
//add to favorite
public void AddtoFav(int position)
{
Image_catName=mAllImageCatName[position];
Image_Url=mAllImages[position];
db.AddtoFavorite(new Pojo(Image_catName, Image_Url));
Toast.makeText(getApplicationContext(),
"Added to Favorite", Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
//remove from favorite
public void RemoveFav(int position)
{
Image_Url=mAllImages[position];
db.RemoveFav(new Pojo(Image_Url));
Toast.makeText(getApplicationContext(), "Removed from
Favorite",Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
//auto play slide show
public void AutoPlay()
{
Update=new Runnable() {
@Override
public void run() {
AutoPlay();
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
handler.removeCallbacks(Update);//when last image play mode goes to Stop
Toast.makeText(getApplicationContext(), "Last Image Auto Play Stoped",
Toast.LENGTH_SHORT).show();
menu.getItem(1).setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
//Show All Menu when Auto Play Stop
ShowMenu();
}
viewpager.setCurrentItem(position);
}
};
handler.postDelayed(Update, 1500);
}
public void ShowMenu()
{
menu.getItem(0).setVisible(true);
menu.getItem(2).setVisible(true);
menu.getItem(3).setVisible(true);
menu.getItem(4).setVisible(true);
}
public void HideMenu()
{
menu.getItem(0).setVisible(false);
menu.getItem(2).setVisible(false);
menu.getItem(3).setVisible(false);
menu.getItem(4).setVisible(false);
}
public void FirstFav()
{
int first=viewpager.getCurrentItem();
String Image_id=mAllImages[first];
List<Pojo> pojolist=db.getFavRow(Image_id);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_id))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = getLayoutInflater();
}
@Override
public int getCount() {
return mAllImages.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_item, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner =(ProgressBar)imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault
(getApplicationContext()));
ImageLoader.getInstance().displayImage(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position], imageView, options, new
SimpleImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason
failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(SlideImageActivity.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
// Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
// .show();
if (checkImage) {
position=viewpager.getCurrentItem();
viewpager.setCurrentItem(position);
} else {
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
}
checkImage = !checkImage;
}
}
@Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
if(dbManager == null){
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
}else if(dbManager.isDatabaseClosed()){
dbManager.init(getApplicationContext());
}
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// unregister listener
super.onPause();
if(!dbManager.isDatabaseClosed())
dbManager.closeDatabase();
sensorManager.unregisterListener(this);
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(Update);
sensorManager.unregisterListener(this);
if(dbManager != null)dbManager.closeDatabase();
}
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection)
myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/EC Images/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully /",
Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
public class ShareTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public ShareTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please Wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/HD Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share Image"));
pDialog.dismiss();
}
}
}
如您所见,代码实现了菜单项,共享,设置为墙纸,保存和缩放。这些是我想要使用的图像按钮,并且已经在上面的xml布局上进行了设置。
这就是我对按钮的看法。但是我不知道在哪里或如何添加它,将它实现到ImageSliderActivity类中。
Button clickButton = (Button) findViewById(R.id.menu_share);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
(new shareTask(SlideImageActivity.this)).execute(Constant.
SERVER_IMAGE_UPFOLDER_CATEGORY+
mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_save);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {position=viewpager.getCurrentItem();
newSaveTask(SlideImageActivity.this)).execute(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_setaswallpaper);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {position=viewpager.getCurrentItem();
Intent intwall=new Intent(getApplicationContext(),SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
Button clickButton = (Button) findViewById(R.id.menu_zoom);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;`
我希望我有道理。如果有人可以指导我朝着正确的方向前进,我将非常感谢你的帮助。基本上,我想在slidingimage活动期间删除溢出菜单,并使用布局底部的按钮来实现这些项目。布局在模拟器中工作并且不会导致错误,但显然当单击按钮时,没有任何反应,因为我不知道将按钮部分添加到滑动活动类的位置,而不会导致多个错误。
非常感谢您提前的时间!