I have created a custom dialog and inside it i create a view page which both have different layout file. Method to show the dialog is in MainActivity.
I inflate a layout to my adapter class where i populate the content. In this layout there is a button. My question is "How can i access the button from the layout that i inflate in my adapter class from my MainActivity. The reason I want to do this is because I want to dismiss the dialog when the button is clicked.
Thanks.
Here is the code of what i have done so far.
MainActivity:
public void ShowPromoOverlay(){
promoOverlay = new Dialog(this);
promoOverlay.requestWindowFeature(Window.FEATURE_NO_TITLE);
promoOverlay.setContentView(R.layout.fragment_overlay);
final List<Promotion> pageArr = new ArrayList<>();
int maxcounter = 5;
if (promotionList.size() < maxcounter) {
maxcounter = promotionList.size();
}
for (int counter = 0; counter < maxcounter; counter++){
pageArr.add(promotionList.get(counter));
}
TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr);
cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
pager = promoOverlay.findViewById(R.id.overlayPager);
pager.setPageMargin(50);
pager.setAdapter(adapter);
com.viewpagerindicator.CirclePageIndicator indicator =
promoOverlay.findViewById(R.id.overlay_page_indicator);
indicator.setViewPager(pager);
indicator.setCurrentItem(0);
promoOverlay.show();
View inlcudeLayout = findViewById(R.id.my_custom_dialog_layout);
ImageView closeBtn = (ImageView) inlcudeLayout.findViewById(R.id.closeBtn);
closeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promoOverlya.dismiss();
}
});
}
fragment_overlay:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/fragment_over"
android:background="#color/bg_orange"
android:layout_width="match_parent"
android:layout_height="match_parent">
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/overlayPager">
<include layout="#layout/my_custom_dialog" />
</cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager>
<com.viewpagerindicator.CirclePageIndicator
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/overlay_page_indicator"
android:layout_alignParentBottom="true"
android:layout_marginBottom="70dp">
</com.viewpagerindicator.CirclePageIndicator>
</RelativeLayout>
my_custom_dialog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_custom_dialog_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp">
<android.support.v7.widget.CardView
android:layout_width="310dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_marginTop="40dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp">
<ImageView
android:id="#+id/closeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_clear_grey_600_24dp"
android:layout_marginTop="7dp"
android:layout_marginRight="7dp"
android:elevation="5dp"
android:layout_gravity="right"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
TestPagerAdapter:
public class TestPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater inflater;
List<Promotion> pageArr;
public TestPagerAdapter(Context context, List<Promotion> pageArr){
this.context = context;
this.pageArr = pageArr;
inflater = ((Activity) context).getLayoutInflater();
}
public TestPagerAdapter(Context context){
this.context = context;
inflater = ((Activity) context).getLayoutInflater();
}
#Override
public int getCount(){
return pageArr.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position){
View view = inflater.inflate(R.layout.my_custom_dialog, container,
false);
TextView prTitle = view.findViewById(R.id.title_pr);
TextView prDescription = view.findViewById(R.id.description_pr);
TextView readMoreBtn = view.findViewById(R.id.readMore);
view.setTag(position);
((ViewPager) container).addView(view);
final Promotion promotion = pageArr.get(position);
prTitle.setText(promotion.getTitle());
prDescription.setText(promotion.getDescription());
return view;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return view == ((View) o);
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
Nice question. You should have to use the interface. let's try this code.
public interface OnButtonClickListner {
public void OnButtonClick();
}
Now You need to pass this interface in the adapter. like this
TestPagerAdapter adapter = new TestPagerAdapter(this, pageArr TestPagerAdapter adapter = new TestPagerAdapter(this,new OnButtonClickListner()
{
#Override
public void OnButtonClick() {
// dismiss dialog here
}
});
Now, You need to change the constructor of Viewpager adapter. like below:
public TestPagerAdapter(Context context, List<Promotion> pageArr,OnButtonClickListner listner){
this.context = context;
this.pageArr = pageArr;
this.onButtonClickListner=listner;
inflater = ((Activity) context).getLayoutInflater();
}
Now you just need to call this listener method from adapter like onButtonClickListner.OnButtonClick(); and the method of popup will call and you will easily dismiss the dialog. you may also pass the argument if you need to require to pass the position of view page.
Click event of read more button like below :
readMoreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onButtonClickListner.OnButtonClick();
}
});
Hope this will help you.
Happy coding.....
Related
I am trying to pick up a single card element kept inside a recycler view and listen to the click and long click events.
However, since you can set the setOnClickListener only on the view, I am finding it difficult to isolate a particular element(card) from the view. As a result, the click event is happening all across the area of the layout.
Please help me isolate a single card from the entire cardview layout and help me write click events to it.
HERE IS MY CODE
CustomAdapter.java
public class CardAdapterLib
extends RecyclerView.Adapter<CardAdapterLib.LibHolder> {
private ArrayList<LibModel> libModel;
public CardAdapterLib(ArrayList<LibModel> data){
this.libModel = data;
}
#Override
public LibHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.recycle_items,parent,false);
// TODO: figure out how to isolate that view
//The listner I have written is getting applied to
the entire layout of R.layout.recycle_items
view.setOnClickListener(LibFragment.myOnClickListener);
return new LibHolder(view);
}
}
My Fragment Class the hosts the recycler view
public class LibFragment extends Fragment {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<LibModel> data;
public static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate
(R.layout.fragment_lib_frgment,container,false);
final CoordinatorLayout LibCoordinatorLayout =
(CoordinatorLayout)view.findViewById(R.id.Lib_coordinatorLayout);
myOnClickListener = new MyOnClickListener(getContext());
recyclerView = (RecyclerView) view.findViewById(R.id.library_rv);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<LibModel>();
for (int i = 0; i < myData.titles.length; i++) {
data.add(new LibModel(myData.titles[i],
myData.authors[i],myData.lang[i],myData.id_[i]));
}
removedItems = new ArrayList<Integer>();
adapter = new CardAdapterLib(data);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), recyclerView ,
new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position)
{Toast.makeText(getActivity(),
"SoftPress",Toast.LENGTH_SHORT).show();
// Launch the Requests Fragment here
}
#Override
public void onLongItemClick(View view, int position) {
Toast.makeText(getActivity(),"Hard Press",Toast.LENGTH_SHORT).show();
//Launch the Delete Fragment here
}
})
);
return view;
}
private static class MyOnClickListener implements View.OnClickListener {
private final Context context ;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
// This Toast happens wherever
I click on the R.layout.fragment_lib_frgment area.
// I want to make it happen only when a single card is clicked!
Toast.makeText(context,"Clicked here DA",Toast.LENGTH_SHORT).show();
removeItem(v);
}
private void removeItem(View v) {
int selectedItemPosition = recyclerView.getChildPosition(v);
RecyclerView.ViewHolder viewHolder
= recyclerView.findViewHolderForPosition
(selectedItemPosition);
TextView =(TextView)viewHolder.itemView.
findViewById(R.id.title_card);
String selectedName = (String) titleTV.getText();
int selectedItemId = -1;
for (int i = 0; i < myData.titles.length; i++) {
if (selectedName.equals(myData.titles[i])) {
selectedItemId = myData.id_[i];
}
}
removedItems.add(selectedItemId);
data.remove(selectedItemPosition);
adapter.notifyItemRemoved(selectedItemPosition);
}
}
}
My Layout Files
<?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="match_parent"
android:orientation="vertical"
android:tag="cards main container">
<android.support.v7.widget.CardView
xmlns:card_view="https://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/card_view"
android:layout_margin="5dp"
card_view:cardCornerRadius="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="6">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:layout_weight="1"
android:id="#+id/lib_counter"
android:textSize="120px"
android:padding="10dp"
android:layout_centerInParent="true"
android:gravity="center" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="4"
android:id="#+id/details_holder">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/title_card"
android:layout_margin="5dp"
android:text="Title"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/author_card"
android:layout_margin="5dp"
android:text="Author"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lang_card"
android:layout_margin="5dp"
android:text="Language"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
And for the Fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/Lib_coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ch330232.pager.Activities.MainActivity">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvRl"
android:layout_gravity="center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/library_rv"
android:scrollbars="vertical" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
You can separate both clicks in your recycleView Adapter with separating Click listeners for both views as below:
#Override
public YourViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("Test", "Parent clicked");
}
});
return new YourViewHolder(itemView);
}
#Override
public void onBindViewHolder(YourViewHolder viewHolder, int i) {
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("Test", "Checkbox clicked");
}
});
}
It is happening every time you click on the fragment because you set it as a click listener for each adapter (or card view) your recycler view has. Use the RecyclerView.addOnItemTouchListener() to activate single items click. Don't add a click listener to every view inside the onBindView method.
All! I'am new in android app. Now I have some problem. I can't see the result of changing list right away (after updating listView in my ListFragment).
For example, i called method addNewItem and I didn't see any changes on the screen. But if I touch ListFragment I will see all my changes.
ListFragment:
public class PointsListFragment extends ListFragment {
PlaceItemsAdapter adapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new PlaceItemsAdapter(
getActivity(), R.layout.place_list_item,
new ArrayList<PlaceItem>());
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void addNewItem(int id, String address) {
adapter.items.add(new PlaceItem(id, address));
adapter.notifyDataSetChanged();
}
private class PlaceItemsAdapter extends ArrayAdapter<PlaceItem> {
private final int viewResourceId;
final public ArrayList<PlaceItem> items;
#Override
public int getCount() {
return items.size();
}
#Nullable
#Override
public PlaceItem getItem(int position) {
return items.get(position);
}
public PlaceItemsAdapter(Context context, int viewResourceId, ArrayList<PlaceItem> items) {
super(context, viewResourceId, items);
this.items = items;
this.viewResourceId = viewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
PlaceItem placeItem = getItem(position);
TextView placeIdTextView = (TextView) v.findViewById(R.id.placeId);
placeIdTextView.setText(String.valueOf(placeItem.getId()));
TextView placeAddressView = (TextView) v.findViewById(R.id.placeAddress);
placeAddressView.setText(placeItem.getAddress());
if (selectedValue == position) {
v.setBackgroundResource(R.drawable.active_item);
}
return v;
}
}
}
My activity xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"[enter image description here][1]
android:padding="2dp">
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/forBorder"
android:orientation="horizontal">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_weight="1" />
<TextView
android:text="проложить маршрут"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/ic_media_ff" />
</LinearLayout>
<fragment
class="com.restfulrobot.cdcapplication.PointsListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_frag" />
</LinearLayout>
Image Example
Thank you, ALL! I found the answer! I called method from another class (no Activity or Fragment). And now I also call method from another class, but i do it through Handler. And it really works fine now!
Something like that:
Message msg = mainActivityHandler.obtainMessage(MainActivity.NEW_MESSAGE, someObjectToAdd);
mainActivityHandler.sendMessage(msg);
I am new to android programming and this task is really need for my school project. Please kindly help me.
I've string array List - (retrieved from csv)
list = new ArrayList<>(Arrays.asList("111,222,333,444,555,666".split(",")));
myList.setAdapter(new ArrayAdapter<String>(getActivity(),R.layout.cell,list));
The result is showing only line by line text of arrayList. I want to add button to each generated line by line to delete clicked row.
Please how can I do this. Thank you for understanding my problem.
You have to create a custom layout xml which having a single item then you will add your button to this layout along with any other items.
CustomLayout.Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />
</RelativeLayout>
Now after creating custom item layout you need listview which holds all items.
MainActivity.xml
.
.
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
.
.
Now in java file just set adapter with our custom layout xml
.
.
list = new ArrayList<String>(Arrays.asList("111,222,333,444,555,666".split(",")));
listview.setAdapter(new MyCustomAdapter(list, context) );
.
.
Custom adapter Class
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.CustomLayout, null);
}
//Handle TextView and display string from your list
TextView tvContact= (TextView)view.findViewById(R.id.tvContact);
tvContact.setText(list.get(position));
//Handle buttons and add onClickListeners
Button callbtn= (Button)view.findViewById(R.id.btn);
callbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
.
}
});
return view;
}
}
We have need ListviewActivity for listing your data
SchoolAdapter which is custom adapter to inflate each individual row
activity_listview which is layout for ListviewActivity
view_listview_row which is required for each individual row
Now create all file as below
For ListviewActivity,
public class ListviewActivity extends AppCompatActivity {
private ListView mListview;
private ArrayList<String> mArrData;
private SchoolAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListview = (ListView) findViewById(R.id.listSchool);
// Set some data to array list
mArrData = new ArrayList<String>(Arrays.asList("111,222,333,444,555,666".split(",")));
// Initialize adapter and set adapter to list view
mAdapter = new SchoolAdapter(ListviewActivity.this, mArrData);
mListview.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
For SchoolAdapter,
public class SchoolAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> mArrSchoolData;
public SchoolAdapter(Context context, ArrayList arrSchoolData) {
super();
mContext = context;
mArrSchoolData = arrSchoolData;
}
public int getCount() {
// return the number of records
return mArrSchoolData.size();
}
// getView method is called for each item of ListView
public View getView(int position, View view, ViewGroup parent) {
// inflate the layout for each item of listView
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.view_listview_row, parent, false);
// get the reference of textView and button
TextView txtSchoolTitle = (TextView) view.findViewById(R.id.txtSchoolTitle);
Button btnAction = (Button) view.findViewById(R.id.btnAction);
// Set the title and button name
txtSchoolTitle.setText(mArrSchoolData.get(position));
btnAction.setText("Action " + position);
// Click listener of button
btnAction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Logic goes here
}
});
return view;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}}
For activity_listview,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#D1FFFF"
android:orientation="vertical">
<ListView
android:id="#+id/listSchool"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0000CC"
android:dividerHeight="0.1dp"></ListView>
For view_listview_row,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="7.5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="7.5dp">
<TextView
android:id="#+id/txtSchoolTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dp"
android:text="TextView"
android:textColor="#android:color/black"
android:textSize="20dp" />
<Button
android:id="#+id/btnAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Click Me" />
At last but not least, do not forgot to add your activity in manifest.xml
Create a custom list view in another file with the only content of each item in the list.
Then create a Custom Adapter extending BaseAdapter and bind it.
Please refer to this website for example.
https://looksok.wordpress.com/tag/listview-item-with-button/
OR
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
I know here we have a lot of questions like mine, but I don't know why none works for me.
My objective: I have an AlertDialog with a ListView with a check box in each row, I can select some of the items, and I wish to make an ArrayList with the elements selected.
For that reason, I'm calling the SetOnclickListener, I put a Log inside the method, but does nothing.
I tried with focusable and clickable almost everywhere, but my Log doesn't appear.
Here My alert Dialog
private void callAdditionalDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(ConfigProductActivity.this);
final View additionalView = layoutInflater.inflate(R.layout.dialog_additional, null);
additionalView.setFocusable(true);
// set the custom dialog components - text, buttons, accountants
TextView titleDialog = (TextView) additionalView.findViewById(R.id.title_additional);
titleDialog.setTypeface(boldFont);
Button buttonAccept = (Button) additionalView.findViewById(R.id.button_accept);
buttonAccept.setTypeface(boldFont);
Button buttonCancel = (Button) additionalView.findViewById(R.id.button_cancel);
buttonCancel.setTypeface(boldFont);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ConfigProductActivity.this);
alertDialogBuilder.setView(additionalView);
final AlertDialog alertD = alertDialogBuilder.create();
alertD.setCanceledOnTouchOutside(false);
//Fill object of additional
final ListView additionalListView = (ListView) additionalView.findViewById(R.id.list_additional);
TextView additionalNotFound = (TextView) additionalView.findViewById(R.id.additional_not_found);
if (!withoutModifiers){
additionalAdapter = new AdditionalAdapter(ConfigProductActivity.this, additionalList);
additionalListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
additionalListView.setAdapter(additionalAdapter);
final ArrayList<ModifierEntity> modifierList = new ArrayList<ModifierEntity>();
additionalListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Object modifier = additionalListView.getAdapter().getItem(position).toString();
Log.d(TAG, "SOMETHIIIIING");
}
});
}
else{
additionalListView.setVisibility(View.GONE);
additionalNotFound.setVisibility(View.VISIBLE);
additionalNotFound.setTypeface(font);
buttonCancel.setVisibility(View.GONE);
}
//End of fill object of additional
buttonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
buttonAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//additional.setText(additionalAdapter.getCount());
additionalBox.setEnabled(true);
alertD.dismiss();
}
});
alertD.show();
}
Here my adapter:
public class AdditionalAdapter extends ArrayAdapter {
private static String TAG = AdditionalAdapter.class.getName();
private List<ModifierEntity> originalData = null;
private ConfigProductActivity activity;
private Typeface font;
private Typeface boldFont;
private static ModifierEntity modifier;
public AdditionalAdapter (ConfigProductActivity activity, List<ModifierEntity> listArray){
super(activity, R.layout.additional_item);
this.activity = activity;
this.originalData = listArray ;
font = Typeface.createFromAsset(activity.getAssets(),"HelveticaNeueThn.ttf");
boldFont = Typeface.createFromAsset(activity.getAssets(), "avgardm.ttf");
}
public static class Row
{
public TextView labelName;
public TextView labelPrice;
public CheckBox check;
}
#Override
public int getCount() {
return originalData.size();
}
#Override
public ModifierEntity getItem(int position) {
return originalData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int colorFont = activity.getResources().getColor(R.color.brown_tataki);
final Row holder;
View rowView = convertView;
// reuse views
if (convertView == null) {
holder = new Row();
LayoutInflater inflater = LayoutInflater.from(activity);
rowView = inflater.inflate(R.layout.additional_item, null);
rowView.setClickable(true);
//rowView.setFocusable(false);
// configure view holder
holder.labelName = (TextView) rowView.findViewById(R.id.additional_name);
holder.labelPrice = (TextView) rowView.findViewById(R.id.additional_price);
holder.check = (CheckBox) rowView.findViewById(R.id.additional_check);
rowView.setTag(holder);
}
else {
holder = (Row) convertView.getTag();
// rowView.setClickable(true);
}
final ModifierEntity itm = originalData.get(position);
holder.labelName.setText(itm.getModifier_name());
holder.labelName.setTypeface(font);
holder.labelName.setTextColor(colorFont);
holder.labelPrice.setText(GlobalParameters.CURRENCY.concat(String.valueOf(itm.getModifier_cost())));
holder.labelPrice.setTypeface(boldFont);
holder.labelPrice.setTextColor(colorFont);
return rowView;
}
}
Here My Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/orange_tataki"
android:text="#string/additional_title"
android:textColor="#color/white"
android:textSize="20sp"
android:gravity="center"
android:id="#+id/title_additional"
android:padding="5dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title_additional"
android:gravity="center"
android:background="#color/white"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_additional"
android:divider="#color/brown_tataki"
android:dividerHeight="0.5dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/list_additional"
android:gravity="center"
android:padding="10dp"
android:visibility="gone"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_not_found"
android:text="#string/additional_not_found"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttons"
android:layout_marginBottom="10dp"
android:layout_below="#+id/additional_not_found"
android:gravity="center"
android:layout_marginTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/button_cancel"
android:background="#color/green_tataki"
android:text="#string/button_cancel"
android:textSize="15sp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_accept"
android:padding="10dp"
android:background="#color/green_tataki"
android:text="#string/button_accept"
android:textSize="15sp"
android:layout_marginLeft="15dp"
/>
</LinearLayout>
</RelativeLayout>
And Here my item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="QUESO"
android:singleLine="true"
android:padding="10dp"
android:textColor="#color/brown_tataki"
android:id="#+id/additional_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/additional_price"
android:padding="10dp"
android:text="Bs. 500"
android:textColor="#color/brown_tataki"
android:layout_toRightOf="#id/additional_name"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="#+id/additional_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp" />
Using interfaces I can solve my problem, this link provided me the solution, and bassically consist in create an interface and implement in my activity.
Like this:
1.- Interface
public interface MyListener {
void folderClicked();
}
2.- Implements the interface in the activity
public class ActivityA extends Activity implements MyListener
3.- You will have to auto override the method folderClicked it will look like this:
#Override
protected void folderClicked() {
// Do your stuff here.
}
4.- Send the activity listener to the adapter with constructor like this:
MyAdpater adapter = new MyAdpater(ActivityA.this);
5.- Your adapter class your code should be like this:
public class TimeLineAdapter extends BaseAdapter {
private MyListener mListener;
public TimeLineAdapter(MyListener listener) {
super();
mListener = listener;
}
holder.iconImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onFolderClicked()
//code to do stuff when the image is clicked
}
I have button, which on clicked displays a listview and on clicking the listview item it must print something on logcat. I implemented this one in such a way that the list view and its listener are present inside the button onclick listener.
All is working well except the listview listener is not getting called(i.e. nothing is printing on logcat when clicked on listview item)
Here is my listener.
public class MyClickListener implements View.OnClickListener {
LinearLayout parent;
LayoutInflater layoutInflater;
Context context;
Home home;
#Override
public void onClick(View view) {
parent = (LinearLayout) home.findViewById(R.id.main_view);
View childLayout = layoutInflater.inflate(R.layout.mylayout, (ViewGroup) view.findViewById(R.id.list_layout));
parent.addView(childLayout, 0);
LinearLayout layout = (LinearLayout) home.findViewById(R.id.main_view);
ListView list = (ListView) layout.findViewById(R.id.list);
list.setAdapter(new MyListAdapter(context));
lsit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("hello Android");
}
});
}
}
mylayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"
android:padding="15dp"
android:divider="#android:color/transparent"
android:dividerHeight="5dp"
android:listSelector="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"/>
</LinearLayout>
Home.java
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button button= (Button) findViewById(R.id.but);
button.setOnClickListener(new MyClickListener(this,this,layoutInflater));
}
}
home.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#color/background">
...
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:id="#+id/main_view">
</LinearLayout>
.....
Can anyone help
Edit 1
MyListAdapter.java
private class MyListAdapter extends BaseAdapter {
String[] items;
LayoutInflater inflater;
Context context;
public MyListAdapter(Context context) {
this.context = context;
Resources resources = context.getResources();
items = new String[]{resources.getString(R.string.q1), resources.getString(R.string.q2), resources.getString(R.string.q3)};
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View view1 = view;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view1 = inflater.inflate(R.layout.list_layout_item, null);
TextView question = (TextView) view1.findViewById(R.id.itemtext);
question.setText(items[i]);
return view1;
}
}
list_layout_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/itemStyle">
<TextView
android:id="#+id/itemtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:drawableRight="#drawable/disclosure_indicator"/>
</LinearLayout>
Remove this code from your onClick() method and implement outside of that onClick() method. Just set Adapter there, but implementation is wrong og onItemClickListener().
lsit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
System.out.println("hello Android");
}
});
Make sure that in your list_item_layout doesn't have any element is stealing event, like button or TextView with setClickable(true).