prevent shortClick when longClick pressed - java

I want to cancel shortClick when LongClicked an item,
I'm using ripple effect material-ripple library in list view but when i long press list item it also call onClick-event
list.setOnItemClickListner not work with MaterialRippleLayout on row item
i have also return true in OnLongClicked but does not work..
also tried and added method in MaterialRippleLayout.java
#Override
public void setOnLongClickListener(OnLongClickListener l) {
super.setOnLongClickListener(l);
childView.setOnLongClickListener(l);
}
and some changes in gesturedetectore
here is my code list_item
<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:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center" >
<com.balysv.materialripple.MaterialRippleLayout
android:id="#+id/list_item_ripple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
app:rippleAlpha="0.2"
app:rippleColor="#585858"
app:rippleDelayClick="true"
app:rippleHover="true"
app:rippleOverlay="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="left"
android:text="Name/Number"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2_dur"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="Duration"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp" >
<TextView
android:id="#+id/textView3_in_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Incoming/Outgoing"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView4_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:gravity="right"
android:text="Time"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</LinearLayout>
</com.balysv.materialripple.MaterialRippleLayout>
& java code
holder.riple.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "item riple clicked "+position, 0).show();
Intent intent = new Intent(getActivity(), PlayerActivity.class);
intent.putExtra("songs", list_path.get(position).toString());
intent.putExtra("name", ""+parts[0]);
intent.putExtra("dur", ""+convertMillis(parts[2]));
intent.putExtra("time", getDate(parts[1].toString()));
startActivity(intent);
}
});
holder.riple.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
list.showContextMenu();
//Toast.makeText(getActivity(), "LongClick", 0).show();
//v.setClickable(false);//v.isClickable();
return true;
}
});
sory for bad english

It looks like you are using a ListView and list_item is the xml for each row. If I'm wrong, stop reading now! But if I'm right, we should consider using the methods setItemClickListener() and setOnItemLongClickListener().
So in your Activity:
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return true; // return true to prevent the `onClick` from being triggered as well.
}
});
Notice the position parameter gets passed in these two methods, so as long as you have a reference to the data set that is being displayed, you can access the exact item that was clicked or long clicked.
It's hard for me to tell why your code wasn't working, so some might not consider this an answer, but I hope this can help. All I know is that things can get really messy when setting click listeners on individual views inside a list view through the adapter.
As a side note, if the only action we want to execute in the on long click action is showing the context menu, then we should consider using registerForContextMenu(listView) and then using the context menu life cycle. One can find more documentation on that practice here.

Actually there is a bug in material-ripple library , already reported there,https://github.com/balysv/material-ripple/issues/15
i have solved my issue,
boolean isLongClick = false;
holder.riple.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "item riple clicked "+position, 0).show();
Intent intent = new Intent(getActivity(), PlayerActivity.class);
intent.putExtra("songs", list_path.get(position).toString());
intent.putExtra("name", ""+parts[0]);
intent.putExtra("dur", ""+convertMillis(parts[2]));
intent.putExtra("time", getDate(parts[1].toString()));
if(isLongClick== false)
{
startActivity(intent);
}
// for click agin on item
isLongClick = false;
}
});
holder.riple.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isLongClick = true;
list.showContextMenu();
//Toast.makeText(getActivity(), "LongClick", 0).show();
//v.setClickable(false);//v.isClickable();
return true;
}
});

Related

Switch between fragment

I have implemented a BottomNavigationView which allows the user to switch between fragments. But now I want to trigger this manually in the program using another button. This button is located in a snackbar. (See code)
Snackbar.make(BLEFragment.this.getView(),"BLE IS NOT ENABLE ! \n go to the settings-tab,...",Snackbar.LENGTH_SHORT)
.setBackgroundTint(Color.rgb(244, 78, 63))
.setTextColor(Color.rgb(255,255,255))
.setAction("Settigs", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
})
.show();
Maybe you can help me here.
If I have formulated the question wrong. I would like to apologize. I do not know how to formulate it differently.
Thank you very much.
Ramsauer René
Snackbar is a control in the Android Support Design Library, which can quickly pop up messages at the bottom of the screen.
Snackbar.make(View view, CharSequence text, int duration)
You can check the parameters and corresponding API
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/galaxyContainer">
</FrameLayout>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/galaxyBottomBar"
android:layout_margin="20dp"
android:paddingVertical="6dp"
app:fabCradleMargin="8dp"
app:fabCradleRoundedCornerRadius="30dp"
app:fabAnchorMode="cradle"
app:fabAlignmentMode="center"
app:elevation="10dp"
app:addElevationShadow="true"
app:fabAnimationMode="slide"
app:fabCradleVerticalOffset="0dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="18dp"
android:orientation="horizontal"
android:weightSum="2">
<com.google.android.material.button.MaterialButton
android:id="#+id/galaxyExploreButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawableTop="#drawable/galaxy_btn_explore"
android:background="#android:color/transparent"
android:text="Explore"
android:textColor="#drawable/galaxy_tab_text"
android:layout_weight="1"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/galaxyGalleryButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:drawableTop="#drawable/galaxy_btn_gallery"
android:background="#android:color/transparent"
android:text="Gallery"
android:textColor="#drawable/galaxy_tab_text"
android:layout_weight="1"/>
</LinearLayout>
</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
And here goes my java code
public void switchTab(boolean isExplore) {
exploreButton.setSelected(isExplore);
galleryButton.setSelected(!isExplore);
FragmentTransaction ft = `enter code here`getSupportFragmentManager().beginTransaction();
ft.replace(R.id.galaxyContainer, isExplore ? new ExploreFragment() : new GalleryFragment());
ft.commit();
}
#Override
public void onClick(View v) {
switchTab(v.getId() == R.id.galaxyExploreButton);
}
Hope this would help.
bottomNavigationView.getMenu() will resolve your issue.try this
Snackbar.make(BLEFragment.this.getView(),"BLE IS NOT ENABLE ! \n go to the settings-tab,...",Snackbar.LENGTH_SHORT)
.setBackgroundTint(Color.rgb(244, 78, 63))
.setTextColor(Color.rgb(255,255,255))
.setAction("Settigs", new View.OnClickListener() {
#Override
public void onClick(View view) {
//Move to next fragment
switchFragment(R.id.more_setting);
}
})
.show();
public void switchFragment(int idd) {
Menu menu = bottomNavigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
if(item.getItemId() == idd){
item.setChecked(true);
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ProgramFragment()).addToBackStack(null).commit();
}
}
}
in activity which holds fragment views
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}

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.

Android Studio: ImageButton's not activating when tapped

I'm working on this App and currently testing it and I'm not quite sure what's wrong. As I tap or hold the Deck Button absolutely nothing happens. Only thing showing up in logcat are Touch Events. I think it might be something wrong with my formatting, but since this is my first time with Java (Only have used assembly for a microprocessors class in the past) I am not sure what it could be.
EDIT: Removed a lot of the extra code unrelated to the problem per suggestion
Here is the MainActivity.java
public class MainActivity extends AppCompatActivity {
int i=0;
int VOA=0;
int VOB=0;
int [] c ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The Draw Control for the Deck. It will only draw if it is in it's 0 state
ImageButton Deck =(ImageButton)(findViewById(R.id.Deck));
assert Deck != null;
Deck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( VOA==0){
VOA=c[i];
i=i+1;
} else if (VOB==0){
VOB=c[i];
i=i+1;
}
}
});
// Uses Collections shuffle to shuffle c
Deck.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
List c= new ArrayList();
Collections.shuffle(c);
return false;
}});
//Discard for Objective A by setting it to 0 and thus updating it's case statement.
ImageButton ObjectiveA =(ImageButton)(findViewById(R.id.ObjectiveA));
assert ObjectiveA != null;
ObjectiveA.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
VOA=0;
return false;
}
});
//Discard for Objective B by setting it to 0 and thus updating it's case statement.
ImageButton ObjectiveB =(ImageButton) (findViewById(R.id.ObjectiveB));
assert ObjectiveB != null;
ObjectiveB.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
VOB=0;
return false;
}
});
}
}
}
Here is the activity_main.xml as well
<?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:layout_width="match_parent"
android:layout_height="match_parent"
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="gallostsp.darkagedeck.MainActivity"
android:background="#drawable/background"
android:screenOrientation="landscape">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Deck"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/VerticalCenterLine"
android:layout_toStartOf="#+id/VerticalCenterLine"
android:background="#drawable/deck"
android:contentDescription="#string/objectives_deck"
android:clickable="true"
android:longClickable="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ObjectiveA"
android:background="#drawable/objectivearea"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/VerticalCenterLine"
android:layout_toEndOf="#+id/VerticalCenterLine"
android:layout_above="#+id/ObjectiveB"
android:contentDescription="#string/objective_a"
android:longClickable="true"
android:clickable="false" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ObjectiveB"
android:layout_below="#+id/HorizontalCenterLine"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#drawable/objectivearea"
android:layout_toRightOf="#+id/VerticalCenterLine"
android:layout_toEndOf="#+id/VerticalCenterLine"
android:layout_alignParentBottom="true"
android:contentDescription="#string/objective_b"
android:longClickable="true"
android:clickable="false" />
</RelativeLayout>
Return true if you consumed the longclickListener()
Deck.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
List c= new ArrayList();
Collections.shuffle(c);
return true; // change to true
}});

Setting OnLongClickListeners to view in listview row intercepts onclick event of listrow

each of my listview's rows holds a number of textviews.
Each textview has singleline set to true and is truncated at the end.
If a textview is truncated, it should be longclickable by the user to open a popup or toast and print the whole text.
So here is my problem:
As soon as I add the OnLongClickListener to a textview, that is part of a row of a listView, the onItemClick method of that listView is not called anymore when the textview is clicked (not longclicked).
XML:
List row item:
<TextView
android:id="#+id/leadingText"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.2"
android:gravity="center"
android:textSize="35sp"
android:singleLine="true"
android:text="20x"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<ExpandableTextView
android:id="#+id/firstLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:singleLine="true"
android:ellipsize="end"
android:gravity="center_vertical"
android:clickable="false"
android:focusable="false"
/>
<TextView
android:id="#+id/secondLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:singleLine="true"
/>
</LinearLayout>
ListView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:divider="#android:color/transparent"
android:dividerHeight="5.0dp"
android:layout_width="match_parent"
android:focusable="true"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Code:
Adding the onItemClickListener to my listView (this happens in a fragment, that holds my listview):
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
UIListEntry item = (UIListEntry) parent.getItemAtPosition(position);
if(selectedKey != item.getId()) {
selectedKey = item.getId();
view.setSelected(true);
} else {
selectedKey = null;
view.setSelected(false);
view.setActivated(false);
}
}
});
Setting the onLongClickListener in my custom TextView ExpandableTextView
private void init() {
this.post(new Runnable() {
#Override
public void run() {
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Layout l = getLayout();
if (l != null) {
int lines = l.getLineCount();
if (lines > 0)
if (l.getEllipsisCount(lines - 1) > 0)
addLongClickListener();
}
vto.removeOnGlobalLayoutListener(this);
}
});
}
});
}
private void addLongClickListener() {
this.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast t = Toast.makeText(SmlApp.getInstance().getApplicationContext(), getText(), Toast.LENGTH_SHORT);
t.show();
return false;
}
});
}
Is there a way to implement an individual onLongClickListener for each textview but keep the onClickListener for the whole row, so the textview does not intercept it and the row is still selectable? Setting the onItemLongClickListener on the listView won't help me, because i don't want the whole row to be longclickable but the individual ExpandableTextView

How to automatically go to next level in a game after completion of first level?

I'm trying to develop a riddle game with levels. First level is in "OneActivity.java" and "activity_one.xml" 2nd level on "TwoActivity.java" and "activity_two.xml" and so on. After the user types the answer to the question in level one, a toast display with "Correct" is displayed if the answer is correct and "Wrong" if it's incorrect. Now, how do I automatically go to next level if the answer is correct but remain on same level until the user inputs the correct answer. Here's my OneActivity.java and activity_one.xml
OneActivity.java:
package com.golo.user.gaunkhanekatha;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class OneActivity extends Activity {
public Button check;
public EditText typeh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
check = (Button)findViewById(R.id.check); //R.id.button is the id on your xml
typeh = (EditText)findViewById(R.id.typeh); //this is the EditText id
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_aboutus, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_one.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:background="#drawable/background"
android:weightSum="1"
android:textAlignment="center"
android:id="#+id/oneque">
<TextView
android:layout_width="300dp"
android:layout_height="200dp"
android:text="What is 2+2?"
android:id="#+id/que"
android:width="255dp"
android:textSize="30dp"
android:layout_margin="50dp"
android:textStyle="italic"
android:gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/typeh"
android:layout_gravity="center_horizontal"
android:text="Type Here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Answer"
android:id="#+id/check"
android:layout_gravity="center_horizontal" />
</LinearLayout>
activity_level.xml:
<?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:background="#drawable/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToOneActivity"
android:background="#drawable/one" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwoActivity"
android:background="#drawable/two" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToThreeActivity"
android:background="#drawable/three" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToFourActivity"
android:background="#drawable/four" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToFiveActivity"
android:background="#drawable/five" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToSixActivity"
android:background="#drawable/six" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToSevenActivity"
android:background="#drawable/seven" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToEightActivity"
android:background="#drawable/eight" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToNineActivity"
android:background="#drawable/nine" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button10"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToTenActivity"
android:background="#drawable/ten" />
<Button
android:id="#+id/button11"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToElevenActivity"
android:background="#drawable/eleven" />
<Button
android:id="#+id/button12"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwelveActivity"
android:background="#drawable/twelve" />
</LinearLayout>
</LinearLayout>
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
//Here create intent to the new activity - for example
//If you wish the user will have time to see the toast, you can use a Handler with post delayed
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent newLevel= new Intent(OneActivity.this, TwoActivity.class);
startActivity(newLevel);
finish(); //finish the activity of the current level
}
}, 3000); //the code inside run() will be executed after 3 seconds so the user can see the toast
}
else
{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
To go to the second level you should add this Intent inside your correct Toast as follows :
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
This should be your code :
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct! Going to Level 2...",
Toast.LENGTH_LONG).show();
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
EDIT
This edit will cancel the Toast when you are on your TwoActivity.class, you have to change some stuff, I'll exaplain to you.
1.- Create a global Toast variable.
private Toast toast;
2.- Initialize it on your onCreate() like this :
toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT);
3.- Then change your two Toast messages to this :
//Correct Toast
toast.setText("Correct! Going to Level 2...");
toast.show();
//Incorrect Toast
toast.setText("Wrong! Try Again");
toast.show();
4.- You want to make a finish() to avoid the back button to return to OneActivity() so you will call it, and it calls onDestroy() so you have to add this method aswell to cancel the Toast
#Override
protected void onDestroy() {
super.onDestroy();
if(toast!= null) {
toast.cancel();
}
}
You can use intents to switch to another activity.
Intent myIntent = new Intent(this, MyActivity.class);
startActivity(myIntent);
You could simply have an if statement. If the answer is correct, create an intent and start activity two, otherwise reloop in activity one or do whatever other behaviour you want to do if the answer is wrong.

Categories