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
Related
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;
}
}
}
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.
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 have implemented an abstract class that has a List View like so:
public abstract class ExampleListFragment extends ExampleFragment{
protected ListView _listView;
public ExampleListFragment () {
super();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Set Up the Bottom Bar
View view = super.onCreateView(inflater, container, savedInstanceState);
addList();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
public void addList() {
_listView = new ListView(getActivity());
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
parms.addRule(RelativeLayout.CENTER_HORIZONTAL);
parms.addRule(RelativeLayout.BELOW, R.id.tableLayout);
_listView.setLayoutParams(parms);
_listView.setClickable(true);
_listView.setFocusable(true);
_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
longListClick(i);
return true;
}
});
_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
listClick(i);
}
});
_layout.addView(_listView);
}
public abstract void longListClick(int pos);
public abstract void listClick(int pos);
}
I then have a class that inherits from this to implement the abstract methods which should be called when clicking an item in the list
public class TwitterFragment extends ExampleListFragment {
private TwitterAdapter _adapter;
//...
#Override
public void onSelected() {
_adapter = new TwitterAdapter(getActivity());
populateAdapter();
}
private void populateAdapter() {
showLoadingTweets();
new TwitterGetTimelineTask().execute(username); //fills adapter with Twitter status info...
}
#Override
public void longListClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
#Override
public void listClick(int pos) {
Toast toast = Toast.makeText(getActivity(),String.format("You have clicked item number: %d",pos),
Toast.LENGTH_SHORT);
toast.show();
}
//...
class TwitterGetTimelineTask extends AsyncTask<String, String, String> {
//...
}
}
However, whenever I click on an Item, it does not appear to even enter onItemClick functions.
Any ideas? help much appreciated.
*EDIT*
As requested, here is the code for my Adapter
public class TwitterAdapter extends BaseAdapter {
private ArrayList<StatusDetails> _statusDetailsArrayList;
private LayoutInflater _inflater;
public TwitterAdapter(Context context) {
_statusDetailsArrayList = new ArrayList<StatusDetails>();
_inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return _statusDetailsArrayList.size();
}
#Override
public Object getItem(int i) {
return _statusDetailsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return _statusDetailsArrayList.get(i).get_id();
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = _inflater.inflate(R.layout.twitter_layout, null);
holder = new ViewHolder();
holder.img_icon = (ImageView) view.findViewById(R.id.statusImage);
holder.text_line1 = (TextView) view.findViewById(R.id.statusText);
holder.text_line2 = (TextView) view.findViewById(R.id.statusDateText);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
Bitmap bmp = _statusDetailsArrayList.get(i).get_profile();
if (bmp == null) {
holder.img_icon.setImageResource(R.drawable.ic_action_twitter);
} else {
holder.img_icon.setImageBitmap(bmp);
}
holder.text_line1.setText(_statusDetailsArrayList.get(i).get_text());
holder.text_line2.setText(_statusDetailsArrayList.get(i).get_date());
return view;
}
public void addStatus(StatusDetails details) {
_statusDetailsArrayList.add(details);
}
public void setStatuses(ArrayList<StatusDetails> details) {
_statusDetailsArrayList = details;
}
public ArrayList<StatusDetails> getEvents() {
return _statusDetailsArrayList;
}
public void removeAll() {
_statusDetailsArrayList.clear();
}
private class ViewHolder {
ImageView img_icon;
TextView text_line1;
TextView text_line2;
}
}
And if needed, the XML of the layout of each list
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/statusImage"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Status"
android:id="#+id/statusText"
android:layout_alignParentTop="true"
android:autoLink="web"
android:textColor="#android:color/white"
android:layout_toRightOf="#+id/statusImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_below="#id/statusText"
android:text="Date"
android:id="#+id/statusDateText"
android:layout_alignBottom="#+id/statusImage"
android:layout_toRightOf="#+id/statusImage" />
Thanks.