I am just starting to work with dialog fragment and there is a lot that I don't know. I have a MainActivity that by clicking on a button opens a DialogFragment, in that DialogFragment I have another button that opens a SecondDialogFragment. The first one works fine but the second one not, I click on the button in the first DialogFragment the screen lose focus with the background but shows nothing. I really don't know what is wrong? I would be grateful if someone could give me a hand.
This is the first DialogFragment where I call the second one by onClick.
DialogFragment.java
ImageButton iconButton = v.findViewById(R.id.user_icon);
iconButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DSelectIcon().show(getFragmentManager(), "DSelectIcon");
}
});
SecondDialogFragment.java
public class DSelectIcon extends DialogFragment{
private View v = null;
private ImageView Selection;
private static final Integer[] items = { R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1 };
public DSelectIcon() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Restore last state for checked position.
}
LayoutInflater inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.grid_icon_event, null);
return createDSelectIcon(v);
}
private AlertDialog createDSelectIcon(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Selection = v.findViewById(R.id.selection);
GridView grid = v.findViewById(R.id.grid);
// grid.setAdapter(new ArrayAdapter<Integer>(this, R.layout.cell,
// items));
grid.setAdapter(new CustomGridAdapter((MainActivity)getActivity(), items));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked postion is" + i,
Toast.LENGTH_LONG).show();
//Selection.setImageResource(items[arg2]);
}
});
return builder.create();
}
public class CustomGridAdapter extends BaseAdapter {
private Activity mContext;
// Keep all Images in array
public Integer[] mThumbIds;
// Constructor
public CustomGridAdapter(MainActivity mainActivity, Integer[] items) {
this.mContext = mainActivity;
this.mThumbIds = items;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
}
Grid_icon_event.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="100dip"
android:gravity="center"
android:horizontalSpacing="5dip"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="40dip" >
</GridView>
</LinearLayout>
FIXED!!!
A stupid mistake, but I forgot to add this:
builder.setView(v);
In the SecondDialogFragment.java method createDSelectIcon
Now it looks like this:
public class DSelectIcon extends DialogFragment{
private View v = null;
private ImageView Selection;
private static final Integer[] items = { R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1, R.drawable.image1,
R.drawable.image1 };
public DSelectIcon() {
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Restore last state for checked position.
}
LayoutInflater inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.grid_icon_event, null);
return createDSelectIcon(v);
}
private AlertDialog createDSelectIcon(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Selection = v.findViewById(R.id.selection);
GridView grid = v.findViewById(R.id.grid);
// grid.setAdapter(new ArrayAdapter<Integer>(this, R.layout.cell,
// items));
grid.setAdapter(new CustomGridAdapter((MainActivity)getActivity(), items));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked postion is" + i,
Toast.LENGTH_LONG).show();
//Selection.setImageResource(items[arg2]);
}
});
builder.setView(v);
return builder.create();
}
public class CustomGridAdapter extends BaseAdapter {
private Activity mContext;
// Keep all Images in array
public Integer[] mThumbIds;
// Constructor
public CustomGridAdapter(MainActivity mainActivity, Integer[] items) {
this.mContext = mainActivity;
this.mThumbIds = items;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
}
Related
how can I set background odd and even row in alert dialog like this ?
AlertDialog.Builder builder = new AlertDialog.Builder(MenuRegister.this);
builder.setTitle("Pilih Tipe User");
builder.setItems(arrData, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
spinerUserType.setText(profesi.get(position).getName());
changeView(profesi.get(position).getId());
role = profesi.get(position).getId();
if (role.equalsIgnoreCase("4")) {
loadSpesialis();
}
}
}).show();
You would have to implement a custom view using builder.setView().
Then, if using a ListView for example, just use something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ...;
}
convertView.setBackgroundColor(position % 2 ? Color.GREY : Color.WHITE);
...
}
cf https://stackoverflow.com/a/9697599/603270
You can set your own adapter instead of set items.
AlertDialog.Builder builder = new AlertDialog.Builder(TestActivity.this);
builder.setTitle("Pilih Tipe User");
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, new String[]{"test1", "test2", "test3"}){
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
if(position %2 == 1)
{
// Set a background color for ListView regular row/item
view.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return view;
}
};
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
}
}).show();
In getView method
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.file_list_row, parent, false);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.layout_id);
//set the background color of alternative row
if (position % 2 == 0) {
linearLayout.setBackgroundColor(Color.parseColor("#BDBDBD"));
} else {
linearLayout.setBackgroundColor(Color.parseColor("#EEEEEE"));
}
return view;
}
In Your raw xml file
<?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">
<LinearLayout
android:id="#+id/layout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
/* Your Views */
</LinearLayout>
</LinearLayout>
you must use from recyclerView and custom adapter like this :
private void selectCategoryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.chips_dialog_layout);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
RecyclerView recyclerView = dialog.findViewById(R.id.recyclerView);
TextView dialogTitle = dialog.findViewById(R.id.dialog_title);
dialogTitle.setText(getResources().getString(R.string.category));
recyclerView.setLayoutManager(new LinearLayoutManager(this));
AdapterCategory _adapter = new AdapterCategory(this, placeCategories);
recyclerView.setAdapter(_adapter);
_adapter.setOnItemClickListener((view, obj, position) -> {
addCategoryChip(obj);
dialog.hide();
});
HelperFunctions.setFont(dialog
.findViewById(android.R.id.content), this, Constants.iranSansFont);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
adapter:
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<PlaceCategory> items = new ArrayList<>();
private OnItemClickListener mOnItemClickListener;
private Typeface mTypeface;
public interface OnItemClickListener {
void onItemClick(View view, PlaceCategory obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public AdapterCategory(Context context, List<PlaceCategory> items) {
this.items = items;
this.mTypeface = HelperFunctions.getTypeface(context);
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public View lyt_parent;
public OriginalViewHolder(View v) {
super(v);
image = v.findViewById(R.id.image);
title = v.findViewById(R.id.type_title);
lyt_parent = v.findViewById(R.id.lyt_parent);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chips_item, parent, false);
HelperFunctions.setFontForAdapter((ViewGroup) v, mTypeface);
vh = new OriginalViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof OriginalViewHolder) {
OriginalViewHolder view = (OriginalViewHolder) holder;
PlaceCategory p = items.get(position);
view.title.setText(p.toString());
view.lyt_parent.setOnClickListener(view1 -> {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view1, items.get(position), position);
}
});
view.lyt_parent.setBackgroundColor(position % 2 == 0 ? Color.GRAY : Color.WHITE);
}
}
#Override
public int getItemCount() {
return items.size();
}
custom layout for dialog :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:padding="#dimen/spacing_large"
android:text="Contact List"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Title" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/spacing_middle"
android:scrollbars="vertical"
android:scrollingCache="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
i hope helped you
I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!
Basically I've a View-pager where I can swipe between 1-6 pictures, using an adapter for that.
In order to "keep track" of the pictures, I implemented a selector which is represented by Image-views inflated using an adapter.
What's next, I'm using setOnPageChangeListener, more exactly the onPageSelected(int position) method to see what's the current Image-view and change its background so it can be differentiated by the rest of them. BUT this doesn't work, although it targets the proper image, the resource is not changed.
Here is some code for a better understanding:
This is where I set the size of the adapter
int poop = profile.getImages().size();
for (int i = 0; i < poop; i++) {
ImageView image = new ImageView(v.getContext());
imageList.add(image);
}
selectorAdapter = new SelectorAdapter(imageList, (android.support.v4.app.FragmentActivity) v.getContext());
selector_view.setAdapter(selectorAdapter);
This is the adapter:
public class SelectorAdapter extends BaseAdapter {
private List<ImageView> mArray = new ArrayList<ImageView>();
private FragmentActivity mContext;
public SelectorAdapter(List<ImageView> mArray, FragmentActivity mContext) {
this.mArray = mArray;
this.mContext = mContext;
}
#Override
public int getCount() {
return mArray.size();
}
#Override
public Object getItem(int position) {
return mArray.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.selector_item, null);
}
return convertView;
}
}
Layout for the adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/selector_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/p_photo_unmarked"
android:layout_marginLeft="5dp"/>
And finally where the magic's supposed to happen:
profilePic.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (selectorAdapter.getItem(position) instanceof ImageView) {
((ImageView) selectorAdapter.getItem(position)).setBackgroundResource((R.drawable.p_photo_marked));
Toast.makeText(getActivity().getApplicationContext(), "position" + position, Toast.LENGTH_SHORT).show();
}
Change the line code
((ImageView) selectorAdapter.getItem(position)).setBackgroundResource((R.drawable.p_photo_marked));
to
((ImageView) selectorAdapter.getItem(position)).setBackground(getResources().getDrawable(R.drawable.p_photo_marked))
EDITED:
((ImageView)((SimpleTabPagerAdapter) selector_view.getAdapter()).getItem(position)).setBackgroundResource((R.drawable.p_photo_marked));
I'm learning Android SDK and I need some advices.
I have custom ListView with BaseAdapter and I want to implement some new feature - Favorite Button.
What I want to do is, when I press the Favorite Button, ListItem goes to the beginning of the list, Favorite image change and all that stuff will be saved in the SharedPrefs.
Someone tell me what I need to do, to make it works?
my existing code:
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_element_list"
>
<ImageView
android:id="#+id/icon"
android:layout_width="150dp"
android:padding="5dp"
android:layout_height="150dp"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/radio" >
</ImageView>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:paddingTop="20dp"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textAlignment="center"
android:text="RadioName"
android:textColor="#color/color1"
android:textSize="30dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:id="#+id/label2"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="fill_parent"
android:textAlignment="center"
android:text="Description.."
android:textColor="#color/color1"
android:textSize="15dp" />
<ImageView
android:id="#+id/favButton"
android:layout_weight="1"
android:layout_width="fill_parent"
android:padding="5dp"
android:layout_height="fill_parent"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/fav_off" >
</ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
BaseAdapter class:
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
public RadioAdapter(Context context, ArrayList<RadioStation> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
RadioStation class:
public class RadioStation
{
public String title;
public String description;
public int imgResId;
//getters and setters
public static Comparator<RadioStation> comparatorByRadioName = new Comparator<RadioStation>()
{
#Override
public int compare(RadioStation radioStation, RadioStation radioStation2)
{
String name1 = radioStation.getTitle().toLowerCase();
String name2 = radioStation2.getTitle().toLowerCase();
return name1.compareTo(name2);
}
};
}
ActivityListView:
public class ActivityMenuList extends Activity implements AdapterView.OnItemClickListener
{
private ListView lvDetail;
private Context context = ActivityMenuList.this;
private ArrayList <RadioStation> myList = new ArrayList <RadioStation>();
private String[] names = new String[] { "one", "two", "three" };
private String[] descriptions = new String[] { "notset", "notset", "notset"};
private int[] images = new int[] { R.drawable.one, R.drawable.two, R.drawable.three };
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setBackgroundDrawableResource(R.drawable.bg1);
setContentView(R.layout.activity_menu_list);
lvDetail = (ListView) findViewById(R.id.list);
lvDetail.setOnItemClickListener(this);
getDataInList();
lvDetail.setAdapter(new RadioAdapter(context, myList));
}
private void getDataInList() {
for(int i=0;i<3;i++) {
RadioStation ld = new RadioStation();
ld.setTitle(names[i]);
ld.setDescription(descriptions[i]);
ld.setImgResId(images[i]);
myList.add(ld);
}
Collections.sort(myList, RadioStation.comparatorByRadioName);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String item = names[i];
Intent e = new Intent(ActivityMenuList.this, ActivityRadioStation.class);
Bundle data = new Bundle();
data.putString("radiostation",item);
e.putExtras(data);
startActivity(e);
}
}
That's a lot of changes you have to do. Let's start with the basic.
Add a boolean to your RadioStation for the favorite state.
public boolean isFavorite;
Next on your getView add the favorite button click listener(add its reference to the viewholder too, but let's keep it simple this time)
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
ListView mListview;
public RadioAdapter(Context context, ArrayList<RadioStation> myList, ListView list) {
this.myList = myList;
this.context = context;
mListView = list;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
convertView.findViewById(R.id.favButton).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
myList.get(position).isFavorite=! myList.get(position).isFavorite;
//reorder mlist
notifyDataSetChanged();
//mListView. smoothscroll here
}
});
((ImageView) convertView.findViewById(R.id.favButton)).setImageResource(myList.get(position).isFavorite?R.drawable.favoriteOn:R.drawable.favoriteOff);
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
I left commented what you should do on the listener. You should be able to continue from here.
When you create your adapter pass the list as the last parameter on the constructor.
Edited: Removed interface. No need to use it here.
Hello i would like to start an activity and also a list view from another activity but i can't understand how to do it.
This is the Expandable adapter
public class MyExpandableAdapter extends BaseExpandableListAdapter
{
#SuppressWarnings("unused")
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
// constructor
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
{
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
// method getChildView is called automatically for each child view.
// Implement this method as per your requirement
#SuppressWarnings("unchecked")
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_view, null);
}
// get the textView reference and set the value
textView = (TextView) convertView.findViewById(R.id.textViewChild);
textView.setText(child.get(childPosition));
// set the ClickListener to handle the click event on child item
/* convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
}
}); */
return convertView;
}
// method getGroupView is called automatically for each parent item
// Implement this method as per your requirement
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = inflater.inflate(R.layout.parent_view, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return 0;
}
#SuppressWarnings("unchecked")
#Override
public int getChildrenCount(int groupPosition)
{
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return false;
}
}
This is my first activity
public class ConversationsListActivity extends ConversationsEssentialActivity{
private String[] drawerListViewItems;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conversations_list);
ActionBar actionBar = getActionBar();
actionBar.show();
FontHelper.applyFont(this, findViewById(R.id.phrasebookList), "fonts/Roboto-Regular.ttf"); /** **/
listView = (ListView) findViewById(R.id.conversationsList);
drawerListViewItems = getResources().getStringArray(R.array.conversations_list_array);
listView.setAdapter(new ArrayAdapter<String>(this,R.layout.conversations_list_items, drawerListViewItems));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
switch (position){
case 0:{
Intent Info = new Intent(ConversationsListActivity.this, ConversationsEssentialActivity.class);
startActivityForResult(Info, position);
setGroupParentsEssential();
setChildDataEssential();
}
break;
}
}
});
}
}
This is my second activity
public class ConversationsEssentialActivity extends Activity{
// Create ArrayList to hold parent Items and Child Items
ArrayList<String> parentItems = new ArrayList<String>();
ArrayList<Object> childItems = new ArrayList<Object>();
ExpandableListView list;
MyExpandableAdapter adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.show();
list = new ExpandableListView(this);
list.setDividerHeight(2);
list.setGroupIndicator(null);
list.setClickable(true);
adapter2 = new MyExpandableAdapter(parentItems, childItems);
adapter2.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
// Set the Adapter to expandableList
list.setAdapter(adapter2);
setContentView(list);
}
// method to add parent Items
public void setGroupParentsEssential()
{
parentItems.add(getResources().getString(R.string.essential_1));
parentItems.add(getResources().getString(R.string.essential_2));
parentItems.add(getResources().getString(R.string.essential_3));
parentItems.add(getResources().getString(R.string.essential_4));
parentItems.add(getResources().getString(R.string.essential_5));
}
// method to set child data of each parent
public void setChildDataEssential()
{
ArrayList<String> child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_1t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_2t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_3t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_4t));
childItems.add(child);
child = new ArrayList<String>();
child.add(getResources().getString(R.string.essential_5t));
childItems.add(child);
}
}
the child_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:paddingLeft="0dp"
android:orientation="vertical"
android:id="#+id/childView" >
<TextView
android:id="#+id/textViewChild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:textSize="20sp"
android:textColor="#75a800"
android:padding="10dp" />
</LinearLayout>
the parent_view.xml
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/textViewGroupName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:textSize="20sp"
android:padding="10dp" />
The first activity, on click, should start the second activity and also launch setGroupParentsEssential(); and setChildDataEssential(); which are declared in the second activity. But on click, it just open the second activity with blank screen.
Does someone provide me an example on how to solve this?
Thank you
If you have created a layout for your activity, try referencing this layout using:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlfile);
...
}
The layout itself should define the listview