I have music background in my app.. and want to stop the music when user reaches the last image in my app. If possible, I would like to make the last image to be name as "last" so that it will be better for code and when it recognize that image name "last" is reached it should be able to stop the music ...or it will be great if the music stops smoothly when last image in my app is reached by viewer..Any idea on how to do that ?
Following are my codes...
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
}
}
Imageadapter.java
import java.io.IOException;
import android.app.WallpaperManager;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private final int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_small);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(context);
try {
myWallpaperManager.setResource(GalImages[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Add an OnPageChangeListener to your viewPager and check if the current image is the last one:
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
if (pos==adapter.getCount()-1) {
oursong.stop();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
Related
When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.
Have an apparently simple task of -
Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.
I already have seen various questions posted on the same topic, I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES
MainActivity.java
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
#Override
public int getItemCount() {
return phones.length;
}
}
MyHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
ItemClickListner.java(Interface)
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield
after i.putExtra("OS NAME ....
add this line
c.startActivity(c,DetailActivity.class);
As you did, in order that changes to be small, try this:
holder.PhoneModel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
Holder will always retain your position.
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
I have developed an app that is suppose to show the image to user using viewpager. But my problem is that my images are not showing in full screen . can any one please suggest the codes for how to make this work ?. Following are my codes..
Mainactivity.java
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
MediaPlayer oursong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start ();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.activity_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
protected void onPause(){
super.onPause();
oursong.release();
}
}
imageadapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
If you really want it to be fullscreen (be careful to the resolution of your assets), you should use a different scale type for your ImageView:
imageView.setScaleType(fullscreen ? ImageView.ScaleType.CENTER_CROP : ImageView.ScaleType.CENTER_INSIDE);
This will crop your image, keeping the initial ratio.
Source
Hi I'm trying to insert a Button into anEmptyView. The only thing I can seem to get to work is the EmptyText where a text value is displayed when the list is empty. This code works for just displaying a textview. How can I successfully add a button to the view?
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.text.format.DateFormat;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.robertrichardson.crimeproofassistant.R.string;
public class crimeListFragment extends ListFragment {
private ArrayList<crime> mcrime;
private boolean mSubtitleVisible;
public static final String TAG = "crimeListFragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getActivity().setTitle(R.string.app_name);
mcrime = crimeLab.get(getActivity()).getcrime();
crimeAdapter adapter = new crimeAdapter(mcrime);
setListAdapter(adapter);
setRetainInstance(true);
mSubtitleVisible = false;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setEmptyText(getResources().getString(string.new_crime_attack_empty_desc));
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
#TargetApi(11)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mSubtitleVisible) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
}
}
ListView listView = (ListView)v.findViewById(android.R.id.list);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// Use floating point context menus on Froyer and Gingerbread
registerForContextMenu(listView);
} else {
// Use contextual action bar on Honeycomb and higher
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
// ActionMode.Callback methods
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.crime_list_item_context, menu);
return true;
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// required but not used in this implementation
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crimeLab crimeLab = crimeLab.get(getActivity());
for (int i = adapter.getCount() - 1; i >= 0; i--) {
if (getListView().isItemChecked(i)) {
crimeLab.deletecrime(adapter.getItem(i));
}
}
mode.finish();
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
// Required, but not used in this implementation
}
public void onDestroyActionMode(ActionMode mode) {
}
});
}
return v;
}
public void onListItemClick(ListView l, View v, int position, long id) {
crime c = ((crimeAdapter)getListAdapter()).getItem(position);
// Start crime Activity
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, c.getId());
startActivity(i);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible && showSubtitle != null) {
showSubtitle.setTitle(R.string.hide_subtitle);
}
}
#TargetApi(11)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
crime crime = new crime();
crimeLab.get(getActivity()).addcrime(crime);
Intent i = new Intent(getActivity(), crimePagerActivity.class);
i.putExtra(crimeFragment.EXTRA_crime_ID, crime.getId());
startActivityForResult(i,0);
return true;
case R.id.menu_item_show_subtitle:
if (getActivity().getActionBar().getSubtitle() != null) {
getActivity().getActionBar().setSubtitle(R.string.subtitle);
mSubtitleVisible = true;
item.setTitle(R.string.hide_subtitle);
} else {
getActivity().getActionBar().setSubtitle(null);
mSubtitleVisible = false;
item.setTitle(R.string.show_subtitle);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.crime_list_item_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
int position = info.position;
crimeAdapter adapter = (crimeAdapter)getListAdapter();
crime crime = adapter.getItem(position);
switch (item.getItemId()) {
case R.id.menu_item_delete_crime:
crimeLab.get(getActivity()).deletecrime(crime);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
private class crimeAdapter extends ArrayAdapter<crime> {
public crimeAdapter(ArrayList<crime> crime) {
super(getActivity(), 0, crime);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If we weren't given a view, inflate one
if (convertView == null) {
convertView = getActivity().getLayoutInflater()
.inflate(R.layout.list_item_crime, null);
}
// Enter the view of this crime Attack
crime c = getItem(position);
TextView titleTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_titleTextView);
titleTextView.setText(c.getTitle());
TextView dateTextView =
(TextView)convertView.findViewById(R.id.crime_list_item_dateTextView);
dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy hh : mm a", c.getDate()).toString());
CheckBox resolvedCheckBox =
(CheckBox)convertView.findViewById(R.id.crime_list_item_resolvedCheckBox);
resolvedCheckBox.setChecked(c.isResolved());
return convertView;
}
}
#Override
public void onResume() {
super.onResume();
((crimeAdapter)getListAdapter()).notifyDataSetChanged();
}
}
Here's my XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#android:id/list"
android:background="#f2f3f4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
<linearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f3f4"
android:orientation="vertical"
>
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new__empty_desc"
/>
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:text="#string/new_attack_empty"
/>
</linearLayout>
</FrameLayout>
public class MainActivity extends Activity {
private CustomBaseAdapter customBaseAdapter;
private ListView lv;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout fl = new FrameLayout(this);
btn = new Button(this);
btn.setText("Hit me");
lv = new ListView(this);
customBaseAdapter = new CustomBaseAdapter(this);
lv.setAdapter(customBaseAdapter);
fl.addView(lv);
fl.addView(btn);
setContentView(fl);
handleVisbility();
}
public void handleVisbility() {
if (customBaseAdapter.getCount() == 0) {
lv.setVisibility(View.GONE);
btn.setVisibility(View.VISIBLE);
} else {
lv.setVisibility(View.VISIBLE);
btn.setVisibility(View.GONE);
}
}
public class CustomBaseAdapter extends BaseAdapter {
private Context context;
View superView;
public CustomBaseAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int arg0) {
return new Object();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
FrameLayout fl = new FrameLayout(context);
Button btn = new Button(context);
btn.setText("Hello, im a Button");
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Yay hit me again", Toast.LENGTH_LONG).show();
}
});
fl.addView(btn);
return fl;
}
}
}
Ok, this is kinda what you want to do here. It shows a ListView, if there is an Item in the List, and will show the Button if the List is Empty. Only thing you have to do, is to call handleVisbility() everytime you make a change to the ListViews content. Especially after you add something to the List.
The default implementation of the ListFragment involves setting up a textView as the empty view for the list.
http://developer.android.com/reference/android/app/ListFragment.html#setEmptyText(java.lang.CharSequence)
You can change this by extending a Fragment and create your own ListView inside it. you can use the code from the ListFragment if you like some of the things it offers.
As an alternative you can try to do getListView().setEmptyView() and set up the view that you need. Again see how they do it in the code in the ListFragment and reproduce it with a different View (instead of TextView use a Button or ImageButton whatever you need)
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/app/ListFragment.java
I've created a custom gallery; however, the "Set wallpaper" button will not set the wallpaper. Here's the wallpaper.java I have. I'm just lost on how to implement OnClickListener and then set my button to use an onclicklistener like so:
buttonName.setOnClickListener(this);
package com.totem;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Gallery.LayoutParams;
import java.io.IOException;
import java.io.InputStream;
public class Wallpaper extends Activity implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String LOG_TAG = "Home";
private static final Integer[] THUMB_IDS = {
R.drawable.andy_small,
};
private static final Integer[] IMAGE_IDS = {
R.drawable.andy,
};
private Gallery mGallery;
private boolean mIsWallpaperSet;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setOnItemClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView parent, View v, int position, long id) {
getWindow().setBackgroundDrawableResource(IMAGE_IDS[position]);
}
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView parent, View v, int position, long id) {
selectWallpaper(position);
}
private synchronized void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(IMAGE_IDS[position]);
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to set wallpaper " + e);
}
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
}
public boolean onTouchEvent(MotionEvent event, Object Action_Down) {
getAction(Action_Down);
selectWallpaper(mGallery.getSelectedItemPosition());
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return THUMB_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(THUMB_IDS[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(android.R.drawable.picture_frame);
return i;
}
}
}
Parsed in 0.242 seconds, using GeSHi 1.0.8.4
Go to http://www.xtensivearts.com/topics/tutorials/ there are video tutorials that will help you with the onclicklisteners
are you set user permission in androidmanifest file for set Wallpaper?
<uses-permission android:name="android.permission.SET_WALLPAPER" />