Problems with the Click event of a ListView in TabHost - java

I have a problem.
I'm developing an application that uses Drawer Layout with reference this example https://developer.android.com/training/implementing-navigation/nav-drawer.html
The lateral menu works correctly, but my fragment (content) load 3 tabs and each has a listview, the problem that I have is that the method onItemClick (setOnItemClickListener) does not work, ie, selecting an item did not solve anything. ¿any idea?. Thanks.!!
PS: sorry for my bad english
PrincipalActivity.java
public class PrincipalActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private String[] mLeftPanel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
initUI();
}
private void initUI(){
mLeftPanel = getResources().getStringArray(R.array.menu_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.dwrMain);
mDrawerList = (ListView) findViewById(R.id.leftPanel);
ArrayList<DrawerOption> items = new ArrayList<DrawerOption>();
items.add(new DrawerOption(R.drawable.ic_plan_visit,mLeftPanel[0]));
items.add(new DrawerOption(R.drawable.ic_clients,mLeftPanel[1]));
items.add(new DrawerOption(R.drawable.ic_search,mLeftPanel[2]));
items.add(new DrawerOption(R.drawable.ic_sinchronize,mLeftPanel[3]));
items.add(new DrawerOption(R.drawable.ic_configure,mLeftPanel[4]));
items.add(new DrawerOption(R.drawable.ic_logout, mLeftPanel[5]));
mDrawerLayout.setDrawerShadow(R.color.listViewBackground, GravityCompat.START);
mDrawerList.setAdapter(new DrawerOptionAdapter(this, items));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
fragmentPlanVisit(position);
getSupportActionBar().setTitle(mLeftPanel[0]);
}
......
mDrawerLayout.closeDrawers();
}
});
......
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem menuItem){
int id = menuItem.getItemId();
if (id == android.R.id.home){
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawers();
}else{
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(menuItem);
}
private void fragmentPlanVisit(int position){
Fragment fragment = new PlanVisitActivity();
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_fragment, fragment)
.commit();
mDrawerList.setItemChecked(position, true);
}
}
}
activity_principal.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dwrMain"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/ContentBackground"/>
<ListView
android:id="#+id/leftPanel"
android:layout_width="250dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:layout_gravity="start"
android:divider="#color/divideColorMenuDrawer"
android:dividerHeight="1dp"
android:background="#color/listViewBackground"
android:layout_weight="1"/>
</android.support.v4.widget.DrawerLayout>
PlanVisitActivity.java
public class PlanVisitActivity extends Fragment {
private TabHost tabHost;
private ListView lstPlanVisitCurse;
private ListView lstPlanVisitDay;
private ListView lstPlanVisitFuture;
private ArrayList<PlanVisits> outLstPlanVisits = new ArrayList<PlanVisits>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_planvisit, container, false);
lstPlanVisitCurse = (ListView)(view.findViewById(R.id.lstPlanVisit_Tab1));
lstPlanVisitCurse.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("PlanVisitActivity", String.valueOf(i));
.....
.....
}
});
......
tabHost = (TabHost)(view.findViewById(R.id.tabHost));
tabHost.setup();
TabHost.TabSpec spec = tabHost.newTabSpec(getResources().getString(R.string.tab1));
spec.setIndicator(getResources().getString(R.string.tab1));
spec.setContent(R.id.tab1);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(getResources().getString(R.string.tab2));
spec.setIndicator(getResources().getString(R.string.tab2));
spec.setContent(R.id.tab2);
tabHost.addTab(spec);
spec = tabHost.newTabSpec(getResources().getString(R.string.tab3));
spec.setIndicator(getResources().getString(R.string.tab3));
spec.setContent(R.id.tab3);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
getListPlanVisit();
return view;
}
private void getListPlanVisit() {
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String s) {
int tab = tabHost.getCurrentTab();
try {
if (tab == 0) {
final PlanVisitsTask tk = new PlanVisitsTask(getActivity().getWindow().getContext(), lstPlanVisitCurse, tab);
tk.execute();
outLstPlanVisits = (ArrayList<PlanVisits>) tk.get();
} else if (tab == 1) {
final PlanVisitsTask tk = new PlanVisitsTask(getActivity().getWindow().getContext(), lstPlanVisitDay, tab);
tk.execute();
outLstPlanVisits = (ArrayList<PlanVisits>) tk.get();
} else if (tab == 2) {
final PlanVisitsTask tk = new PlanVisitsTask(getActivity().getWindow().getContext(), lstPlanVisitFuture, tab);
tk.execute();
outLstPlanVisits = (ArrayList<PlanVisits>) tk.get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
}
}
activity_planvisit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/ContentBackground"
android:focusable="false"
android:focusableInTouchMode="false">
<TabHost
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabHost"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lstPlanVisit_Tab1"
android:divider="#color/divideColorlistView"
android:dividerHeight="1dp"
android:background="#color/listViewBackground"
android:choiceMode="singleChoice"/>
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lstPlanVisit_Tab2"
android:divider="#color/divideColorlistView"
android:dividerHeight="1dp"
android:background="#color/listViewBackground"
android:choiceMode="singleChoice" />
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/lstPlanVisit_Tab3"
android:divider="#color/divideColorlistView"
android:dividerHeight="1dp"
android:background="#color/listViewBackground"
android:choiceMode="singleChoice" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>

Looking for answers, i found this link onListItemClick is not working for listview?, make the adjustments and now works correctly.

Related

Why does listview is not showing on my emulator?

I'm making simple listview of therapies and the list is not showing on the emulator. I've upgraded and downgraded my api from 22 to 30 and change relative layout to linear layout but still the list is not showing.
activty_stress.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="9"
android:background="#83BCD4"
tools:context=".stress">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="18pt" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"/>
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stress);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==0){
//clicked therapy1
startActivity(new Intent(stress.this,Therapy1.class));
} else if (position==1){
//clicked therapy2
}else{
}
}
});
}
Heyy try replacing your RelativeLayout with LinearLayout, or remove weightSum because weightSum cannot be used with RelativeLayout
Replace with this code.
Note: Whenever you give textSize, give it in sp not in Pixel.
activty_stress.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#83BCD4"
android:orientation="vertical">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Find your relaxation"
android:textColor="#color/white"
android:textSize="30sp" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp" />
</RelativeLayout>
stress.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listview);
List<String> list = new ArrayList<>();
list.add("Therapy1");
list.add("Therapy2");
list.add("Therapy3");
list.add("Therapy4");
list.add("Therapy5");
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
//clicked therapy1
// startActivity(new Intent(stress.this,Therapy1.class));
} else if (position == 1) {
//clicked therapy2
} else {
}
}
});
}
Output:

RecyclerView not replacing detail pane with fragment on item click

Everytime I click a recycler view item on a tablet, it opens an activity rather than replacing the detail pane with a fragment.
The following line of code is what I use to detect wheter the detail pane is present:
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
Any ideas on the correct location to put this line of code?
activity 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">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
>
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
sw600dp activity XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.widget.Toolbar
android:id="#+id/masterToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/detailBackgroundToolbar"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:id="#+id/singleline_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="#+id/md_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
</LinearLayout>
</android.widget.Toolbar>
<RelativeLayout
android:id="#+id/master_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHorizontal_weight="2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="#+id/divider"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<View
android:id="#+id/divider"
android:layout_width="1dp"
android:layout_height="0dp"
android:background="?attr/dividerColor"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toBottomOf="#+id/masterToolbar" />
<android.widget.Toolbar
android:id="#+id/detailBackgroundToolbar"
android:layout_width="0dp"
android:layout_height="?actionBarSize"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_weight="3"
app:layout_constraintStart_toEndOf="#+id/masterToolbar"
app:layout_constraintTop_toTopOf="parent" />
<android.support.v7.widget.CardView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="4dp"
app:cardCornerRadius="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_dualline"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v7.widget.CardView>
<View
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/divider"
app:layout_constraintTop_toBottomOf="#+id/detailBackgroundToolbar" />
</android.support.constraint.ConstraintLayout>
Fragment class
public class MyFragment extends Fragment {
public MyFragment() {}
List<Product> wcList;
RecyclerView mRecyclerView;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
*/
public boolean mTwoPane;
public static MyFragment newInstance() {
return new MyFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
mRecyclerView = view.findViewById(R.id.recyclerView_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));
myList = new ArrayList<>();
String[] items = getResources().getStringArray(R.array.product_names);
String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
for (int n = 0; n < items.length; n++){
Product desserts = new Product();
desserts.setProductName(items[n]);
wdessertsc.setProductDescriptions(itemDescriptions[n]);
myList.add(desserts);
}
MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);
mRecyclerView.setAdapter(listAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;
super.onActivityCreated(savedInstanceState);
}
}
Adapter class
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
public boolean mTwoPane;
private Context mCtx;
private List<Product> myList;
public MyListAdapter(Context mCtx, List<Product> myList) {
this.mCtx = mCtx;
this.myList = myList;
}
#NonNull
#Override
public MyListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
return new MyListAdapter.MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyListAdapter.MyViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
final Product product = myList.get(holder.getAdapterPosition());
holder.textviewTitle.setText(product.getProductName());
holder.textviewSubtitle.setText(product.getPRoductDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Fragment newFragment;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
newFragment = new FragmentProduct1();
} else {
newFragment = new FragmentProdcut2();
}
MyActivity activity = (MyActivity) v.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
intent = new Intent(v.getContext(), Product1Activity.class);
} else {
intent = new Intent(v.getContext(), Product2Activity.class);
}
mCtx.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return myList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayout;
TextView textviewTitle, textviewSubtitle;
StationViewHolder(View itemView) {
super(itemView);
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
textviewTitle = itemView.findViewById(R.id.listitem_title);
textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
}
}
}
This line mTwoPane = itemView.findViewById(R.id.detail_container) != null; from your view holder will always be false.
Why?
Because, your detail_container is not part of your view holder's item container, so itemView will always return null for your view. instead pass your boolean flag from your fragment to your adapter !
I think you are checking item two pan with recyclerview item xml
mTwoPane = itemView.findViewById(R.id.detail_container) != null;
That you can check while constructing recyclerview adapter and save it from the activity content view itself.

Call OnClick with ImageView in other layout file

I have one Activity, which is MainActivity with a NavigationDrawer. So, when I click on my first item in my NavigationDrawer, I open a Fragment in MainActivity. In this Fragment, I inflate a layout with an ImageView. But when I click the ImageView, it does not work. Can you explain me why that's not work if it's possible? Thanks.
Here's the onClick implementation in my Fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_stream, container, false);
mItemsContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.container_items);
mItemsContainer.setOnRefreshListener(this);
//Pub perso
View rootViewx = inflater.inflate(R.layout.ad_item, container, false);
ImageView imgFavorite = rootViewx.findViewById(R.id.adviewperso);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "MYURL";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Toast.makeText(getActivity(),
"Pub appuyé !",
Toast.LENGTH_LONG).show();
}
});
//TEST2
CardView cardtest = rootViewx.findViewById(R.id.adCard);
cardtest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "MYURL";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Toast.makeText(getActivity(),
"Pub appuyé !",
Toast.LENGTH_LONG).show();
}
});
//TEST2
//Fin pub perso
mMessage = (TextView) rootView.findViewById(R.id.message);
mFabButton = (FloatingActionButton) rootView.findViewById(R.id.fabButton);
mFabButton.setImageResource(R.drawable.ic_action_new);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
itemsAdapter.setOnMoreButtonClickListener(new AdvancedItemListAdapter.OnItemMenuButtonClickListener() {
#Override
public void onItemClick(View v, Item obj, int actionId, int position) {
switch (actionId) {
case R.id.action_repost: {
if (obj.getFromUserId() != App.getInstance().getId()) {
if (obj.getRePostFromUserId() != App.getInstance().getId()) {
repost(position);
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.msg_not_make_repost), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), getActivity().getString(R.string.msg_not_make_repost), Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.action_share: {
onPostShare(position);
break;
}
case R.id.action_report: {
report(position);
break;
}
case R.id.action_remove: {
remove(position);
break;
}
}
}
});
final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(itemsAdapter);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(dy > 0) {
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (!loadingMore) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount && (viewMore) && !(mItemsContainer.isRefreshing())) {
loadingMore = true;
Log.e("...", "Last Item Wow !");
getItems();
}
}
}
}
});
mFabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewItemActivity.class);
startActivityForResult(intent, STREAM_NEW_POST);
}
});
if (itemsAdapter.getItemCount() == 0) {
showMessage(getText(R.string.label_empty_list).toString());
} else {
hideMessage();
}
if (!restore) {
showMessage(getText(R.string.msg_loading_2).toString());
getItems();
}
return rootView;
}
And the layout containing adviewperso looks like the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:background="#F5F5F5"
android:clickable="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="#+id/adCard"
app:cardCornerRadius="#dimen/spacing_medium"
app:cardElevation="#dimen/spacing_xsmall"
app:cardUseCompatPadding="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:tint="#color/sponsored"
android:src="#drawable/ic_sponsored"
android:visibility="visible" />
<TextView
android:id="#+id/adTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:text="#string/label_sponsored"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/sponsored"
android:textStyle="normal"
android:visibility="visible" />
</LinearLayout>
<RelativeLayout
android:minHeight="64dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<ImageView
android:id="#+id/adviewperso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:srcCompat="#drawable/pub" />
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="#string/banner_ad_unit_id"
android:visibility="invisible"
ads:adSize="320x150">
</com.google.android.gms.ads.NativeExpressAdView>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I do not have any errors when I compile or when I run my app.
I would suggest two things. Make the ImageView clickable from the layout and I think the AdView is overlapping the ImageView which is making it not clickable.
So the views under the RelativeLayout should look like the following.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:minHeight="64dp"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<ImageView
android:id="#+id/adviewperso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
ads:srcCompat="#drawable/ic_add" />
<com.google.android.gms.ads.NativeExpressAdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/adviewperso"
android:visibility="invisible"
ads:adSize="320x150"
ads:adUnitId="#string/banner_ad_unit_id"/>
</RelativeLayout>
Update
You are returning rootView from your onCreateView. You cannot inflate multiple layouts in a single Fragment. So the layout you are inflating using View rootViewx = inflater.inflate(R.layout.ad_item, container, false); will not have any effect if you are not returning the same layout from onCreateView.
I hope you have the ImageView in your fragment_stream layout or it includes the ad_item layout. So if the ad_item layout is included in your fragment_stream layout, then you can get the view id associated with the layout easily without having inflating it separately.
If you have two Fragment, then you need two separate Fragment class where you inflate ad_item and fragment_stream separately. And then, you join them together using another Fragment as a holder of these two fragments.

Can't enable contextual action mode with CustomAdapter<MyClass>

I'm trying to enable contextual action mode in a ListView with my custom adapter inherited from ArrayAdapter<MyClass>. And can't. Just nothing is happening on long click. Neither in UI, nor in logs.
When I use ArrayAdapter<String> everything's working right. What is my mistake, please explain me. Thanks in advance.
Here are my files.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String TAG = "LOG";
ListView listView;
ArrayAdapter<Note> adapter; // It doesn't work.
//ArrayAdapter<String> adapter; // It works.
List<Note> notes;
static final int REQUEST_CODE_NOTE = 1;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(android.R.id.list);
notes = new ArrayList<>();
notes.add(new Note("First note"), new Note("Second note"));
adapter = new NoteAdapter(this, notes);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
Log.d(MainActivity.TAG, "onCreateActionMode");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
Toast.makeText(MainActivity.this, "onCreateActionMode", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
actionMode.finish();
return true;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
//registerForContextMenu(listView);
btnAdd = (Button) findViewById(R.id.add_button);
btnAdd.setOnClickListener(this);
}
}
NoteAdapter.java
class NoteAdapter extends ArrayAdapter<Note> {
private AppCompatActivity parentActivity;
NoteAdapter(Context context, List<Note> notes) {
super(context, R.layout.note_item, notes);
this.parentActivity = (AppCompatActivity) context;
}
#NonNull
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final Note note = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.note_item, parent, false);
convertView.setLongClickable(true);
}
((TextView) convertView.findViewById(R.id.note)).setText(note.getText());
((TextView) convertView.findViewById(R.id.date_last_edited)).setText(note.getFormattedDate());
return convertView;
}
}
Note.java
class Note {
private String note;
private Calendar date_last_edited;
Note(String note) {
this.note = note;
this.date_last_edited = Calendar.getInstance();
}
Note(String note, Calendar date) {
this.note = note;
this.date_last_edited = date;
}
void setText(String text) {
this.note = text;
this.date_last_edited = Calendar.getInstance();
}
String getText() {
return this.note;
}
Calendar getDate() {
return this.date_last_edited;
}
String getFormattedDate() {
SimpleDateFormat formattedDate= new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return "Last edited: " + formattedDate.format(date_last_edited.getTime());
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="0dp"
android:paddingStart="0dp"
android:paddingRight="0dp"
android:paddingEnd="0dp"
android:paddingTop="0dp"
android:background="#color/colorBackground">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="2dp"
android:id="#+id/add_button"
android:text="#string/add_button"
android:background="#drawable/button_background"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/add_button"
android:padding="0dp"
android:layout_marginLeft="2dp"
android:layout_marginStart="2dp"
android:layout_marginRight="2dp"
android:layout_marginEnd="2dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="0dp"
android:divider="#android:color/transparent"
android:dividerHeight="6dp"/>
</RelativeLayout>
note_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/note_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/note_margin"
android:paddingLeft="#dimen/note_margin"
android:paddingRight="#dimen/note_margin"
android:paddingTop="#dimen/note_margin"
android:background="?android:attr/activatedBackgroundIndicator"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
tools:context="ru.geekbrains.lesson7.simplenotes.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:padding="10dp"
android:id="#+id/note"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Test note"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/note"
android:layout_alignParentBottom="true"
android:padding="10dp"
android:id="#+id/bottom_panel" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/date_last_edited"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Date: 01.01.2017 12:33:21"/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="#+id/delete_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:contentDescription="Delete note"
android:src="#drawable/delete"/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="#+id/edit_button"
android:layout_toLeftOf="#id/delete_button"
android:layout_toStartOf="#id/delete_button"
android:contentDescription="Edit note"
android:src="#drawable/edit"/>
</RelativeLayout>
</RelativeLayout>
context_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title="#string/delete_all_context_menu"
android:id="#+id/delete_all_context"
android:icon="#android:drawable/ic_menu_delete">
</item>
</menu>

setOnClickListener not firing with custom adapter and custom ListView

I've been spending a few hours on a problem and I still can't figure it out. The setOnClickListener in HotelOverviewFragment is not firing when I click an item in my ListView. However, the setOnClickListener does work from my custom adapter (NowArrayAdapter).
My question is: why the setOnClickListener not working in HotelOverviewFragment (Class where the ListView is shown)?
Here's a list of what I've tried:
Setting android:focusable="false", android:focusableInTouchMode="false", android:descendantFocusability="blocksDescendants" in the hotel_row_layout.xml and fragment_hotel_overview.xml.
Setting android:clickable on true and false. Both didn't work.
Changing from BaseAdapter implementation to arrayAdapter.
I tried different listeners in HotelOverviewFragment: setOnClickListener, setOnItemClickListener, setOnItemSelectedListener and setOnTouchListener. Unfortunately, none of those worked for me.
Here's my code:
Custom adapter
public class NowArrayAdapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> values;
private Typeface typeface;
private static Hashtable fontCache = new Hashtable();
private LayoutInflater inflater;
private TextView item;
public NowArrayAdapter(Context context, ArrayList<String> commandsList) {
super(context, R.layout.hotel_row_layout, commandsList);
this.context = context;
values = new ArrayList<String>();
values.addAll(commandsList);
typeface = getTypeface(this.context, "fonts/Roboto-Light.ttf");
inflater = LayoutInflater.from(this.context);
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public View getView(int position, View convertView, ViewGroup parent) {
String myText = getItem(position);
if(convertView == null) {
convertView = inflater.inflate(R.layout.hotel_row_layout, parent, false);
item = (TextView) convertView.findViewById(R.id.maps_button);
item.setTypeface(typeface);
convertView.setTag(item);
} else {
item = (TextView) convertView.getTag();
}
item.setText(myText);
//myListItem.descText.setTextSize(14);
convertView.setOnClickListener(new View.OnClickListener() {
// WORKS!
#Override
public void onClick(View view) {
Log.d("click", "Don't look at me!");
}
});
return convertView;
}
}
Fragment
public class HotelOverviewFragment extends Fragment {
private static Hashtable fontCache = new Hashtable();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_hotel_overview, container, false);
ListView list = (ListView) v.findViewById(android.R.id.list);
// Set up listview and buttons
setUp(v, list);
// Inflate the layout for this fragment
return v;
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public void setUp(View v, ListView l){
TextView address = (TextView) v.findViewById(R.id.content);
TextView header = (TextView) v.findViewById(R.id.header);
TextView hotelName = (TextView) v.findViewById(R.id.hotelName);
Typeface typeface = getTypeface(getActivity(), "fonts/Roboto-Light.ttf");
address.setText("some street \nZipCode, City \nCountry \nEmail \nphoneNumber");
address.setTypeface(typeface);
header.setText("Hotel info");
header.setTypeface(typeface);
header.setTextSize(20);
hotelName.setText("Hotel name");
hotelName.setTypeface(typeface);
// Set up button
ArrayList<String> n = new ArrayList<String>();
n.add(0, "More info");
// Show button
NowArrayAdapter adapter = new NowArrayAdapter(getActivity(), n);
l.setAdapter(adapter);
// THIS IS THE STUFF I'VE BEEN TRYING
try {
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "Success");
}
});
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
});
l.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
l.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("click", "Success");
return false;
}
});
}catch (Exception e){
Log.d("click", e + "");
}
}
}
Layout xml of HotelOverviewFragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example"
android:background="#ffebebeb">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/banner"
android:id="#+id/hotelBanner"
android:layout_gravity="top"
android:adjustViewBounds="false"
android:scaleType="fitXY" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hotelname"
android:id="#+id/hotelName"
android:gravity="center"
android:textSize="40dp"
android:layout_alignBottom="#+id/hotelBanner"
android:layout_alignParentRight="false"
android:layout_alignParentLeft="false"
android:textColor="#ffc4c4c4"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="0dp"
android:background="#drawable/header_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Header"
android:layout_toRightOf="#+id/headerImage"
android:layout_centerVertical="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/headerImage"
android:src="#drawable/ic_action_live_help"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:background="#drawable/content_card">
<TextView
android:id="#+id/content"
android:layout_gravity="left|center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
The custom xml for a listview item
<?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">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/content_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/maps_button"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
<ImageView
android:src="#drawable/ic_action_arrow_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="false"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="false"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</LinearLayout>
Thanks in advance.
Thanks to Daniel Nugent's suggestion I got it working. Removing the convertView.setOnClickListener() is part of the answer. I think it was blocking the other listeners in the HotelOverviewFragment.
My next mistake was that I used setOnClickListener on a ListView for testing.
setOnClickListener should be used for buttons not ListViews.
So after removing setOnClickListener all the other listeners started working.
Thanks for your time.

Categories