I am new at app developing. I'm currently working on an app with tabview and an ExpandableListView in one of the tabs, thus why i'm trying to use an expandablelistview in a fragment.
My expandablelistview appears flawlessly when run directly from an activity, but when i'm trying to run it from a fragment, it appears blank.
HomeFragment.java
public class HomeFragment extends Fragment {
ExpandableListView expandableListView;
View homeFragmentView;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
homeFragmentView = inflater.inflate(R.layout.fragment_home, container, false);
expandableListView = (ExpandableListView) homeFragmentView.findViewById(R.id.exp_listview);
return homeFragmentView;
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState){
List<String> Headings = new ArrayList<String>();
List<String> L1 = new ArrayList<String>();
List<String> L2 = new ArrayList<String>();
List<String> L3 = new ArrayList<String>();
HashMap<String, List<String>> ChildList = new HashMap<String, List<String>>();
String heading_items[] = getResources().getStringArray(R.array.header_titles);
String h1[] = getResources().getStringArray(R.array.h1_items);
String h2[] = getResources().getStringArray(R.array.h2_items);
String h3[] = getResources().getStringArray(R.array.h3_items);
for(String title : heading_items){
Headings.add(title);
}
for (String title : h1){
L1.add(title);
}
for (String title : h2){
L2.add(title);
}
for (String title : h3){
L3.add(title);
}
ChildList.put(Headings.get(0), L1);
ChildList.put(Headings.get(1), L2);
ChildList.put(Headings.get(2), L3);
ExpListViewAdapter expListViewAdapter = new ExpListViewAdapter(getActivity(), Headings, ChildList);
expandableListView.setAdapter(expListViewAdapter);
}
}
Adapter class:
public class ExpListViewAdapter extends BaseExpandableListAdapter {
private List<String> header_titles;
private HashMap<String, List<String>> child_titles;
private Context ctx;
ExpListViewAdapter(Context ctx, List<String> header_titles, HashMap<String, List<String>> child_titles){
this.ctx = ctx;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
#Override
public int getGroupCount() {
return header_titles.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return child_titles.get(header_titles.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String title = (String)this.getGroup(groupPosition);
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.parent_layout, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setTypeface(null, Typeface.BOLD);
textView.setText(title);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String)this.getChild(groupPosition,childPosition);
if (convertView == null){
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child_layout, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.child_item);
textView.setText(title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
header (parent) layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#151515">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World"
android:textColor="#ffffff"
android:textSize="25dp"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
child layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#252525">
<TextView
android:id="#+id/child_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World"
android:textColor="#f9f9f9"
android:gravity="center_vertical"
android:textSize="20dp"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(), "Home");
viewPagerAdapter.addFragments(new Group_Invites(), "Group invites");
viewPagerAdapter.addFragments(new New_Group(), "New group");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super (fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles.get(position);
}
}
I tried your code and it is working fine. Also share your activity code from where you have opened your fragment class.
Related
I have created a BottomSheetDialog with a GridView, but I know that BottomSheetDialog can't set a title using the method .setTitle(), so how can I set a title on the dialog?
Here's my code:
Activity:
customAdapter = new CustomAdapter(this);
GridView gridView = new GridView(this);
gridView.setAdapter(customAdapter);
gridView.setNumColumns(5);
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(this);
bottomSheetDialog.setContentView(gridView);
bottomSheetDialog.show();
CustomAdapter:
private final LayoutInflater inflater;
private List<String> sizeCodes;
public CustomAdapter(Context context) {
this.sizeCodes = Collections.emptyList();
this.inflater = LayoutInflater.from(context);
}
public CustomAdapter addItems(List<SizeData> items) {
sizeCodes = new ArrayList<>();
for (SizeData item : items)
sizeCodes.add(item.getSize());
notifyDataSetChanged();
return this;
}
#Override
public int getCount() {
return sizeCodes.size();
}
#Override
public String getItem(int position) {
return sizeCodes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.item_size_picker, parent, false);
((TextView) convertView.findViewById(R.id.content)).setText(sizeCodes.get(position));
return convertView;
}
item_size_picker:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/content"
style="#style/Base.TextAppearance.AppCompat.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
I want to display String[] arrayTitles on top of String[] arrayDescriptions, which should be sub items, in the list view. How am I supposed to do this? Posting a working version of this code would be much appreciated.
ListView listview = (ListView)findViewById(R.id.listview);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_list);
String[] arrayTitles = formattedTitles.split(",");
String[] arrayDescriptions = formattedDescriptions.split(",");
for (int i = 0; i < arrayLocations.length; i++) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(context, android.R.layout.simple_list_item_1, arrayTitles);
listview.setAdapter(arrayAdapter);
}
}
I am posting answer using Custom Adapter, you can just create one class CustomAdapter.java
package com.example.your.package.name;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
Context mContext;
String[] arrayTitles;
String[] arrayDescriptions;
public CustomAdapter(Context mContext,String[] arrayTitles,String[] arrayDescriptions)
{
this.mContext = mContext;
this.arrayTitles = arrayTitles;
this.arrayDescriptions = arrayDescriptions;
}
#Override
public int getCount() {
return arrayTitles.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(parent.getContext());
v = vi.inflate(R.layout.item_list_row, null);
}
TextView tvTitle = (TextView) v.findViewById(R.id.txtTitle);
TextView tvDesc = (TextView) v.findViewById(R.id.txtDesc);
tvTitle.setText(arrayTitles[position]);
tvDesc.setText(arrayDescriptions[position]);
return v;
}
}
create one item_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:padding="5dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/txtDesc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Description"
android:paddingLeft="5dp"
android:textStyle="normal"/>
</LinearLayout>
and replace ArrayAdapter with CustomAdapter in your Activity(having ListView)
your onCreate method will look like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
ListView listview = (ListView)findViewById(R.id.listview);
String[] arrayTitles = formattedTitles.split(",");
String[] arrayDescriptions = formattedDescriptions.split(",");
CustomAdapter arrayAdapter = new CustomAdapter(ListViewActivity.this, arrayTitles,arrayDescriptions);
listview.setAdapter(arrayAdapter);
}
I think It will work fine, If it will not work let me suggest what else you want, I will edit my answer
Thank you
Use two types view
I posting working code below main logic in getview().
public class FriendsList extends BaseAdapter{
private Context context;
private final int Separater_Type = 0;
private final int List_Type = 1;
ArrayList< FriendsInfo> list=new ArrayList<FriendsInfo>();
private ActiveList mActiveList = null;
ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();
public FriendsList(Context context,ArrayList<FriendsInfo> list,ActiveList activeList){
this.context=context;
mActiveList = activeList;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return list.get(position).getType();
}
ViewHolder holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
int rowType;
rowType = list.get(position).type;
if (convertView == null) {
holder = new ViewHolder();
switch (rowType){
case Separater_Type:
convertView = View.inflate(context, R.layout.activelistheader, null);
holder.headerName = (TextView) convertView.findViewById(R.id.list_separator);break;
case List_Type:
convertView = View.inflate(context, R.layout.rowlist, null);
holder.avatar = (CircleImageView)convertView.findViewById(R.id.avatarimage);
holder.headerName = (TextView) convertView.findViewById(R.id.name);
holder.selectMark = (ImageView) convertView.findViewById(R.id.select_img);
//holder.select_img = (ImageView)convertView.findViewById(R.id.select_img);
break;
}
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
if(list.get(position).type ==0){
holder.headerName.setText(list.get(position).name);
}else{
}
return convertView;
}
private class ViewHolder {
CircleImageView avatar;
TextView headerName;
ImageView selectMark;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return true;
}
}
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!
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