Android: how to set up CardView OnLongClick()? - android

I have a RecyclerView list of CardViews. I click on a CardView and it uses an intent to launch a new activity, which shows a detail CardView to the user. I want to add a LongClick to that new CardView that will launch a Dialog to ask the user if they would like to delete the CardView. I tried the set up below. The Dialog does not launch and I don't see the Toast. What am I missing here?
public class CardViewDetails extends AppCompatActivity {
int position;
CardView cardView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
CardView cardView = (CardView) findViewById(detsinglecard_view);
cardView.setOnClickListener((View.OnClickListener) this);
cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(CardViewDetails.this,"Dialog Test",Toast.LENGTH_SHORT).show();
android.app.FragmentManager fm = getFragmentManager();
DeleteCardViewFragment delCardViewDialog = new DeleteCardViewFragment();
delCardViewDialog.show(fm,"delcardview dialog");
return true;
}
});
activity_details:
<?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:background="#FFFFFF"
tools:context="com.wimso.v060B.CardViewDetails">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" >
</include>
<RelativeLayout
android:id="#+id/cardViewDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background4main"
android:layout_marginTop="6dp"
android:layout_marginStart="6dp"
android:layout_marginLeft="6dp"
android:layout_marginEnd="6dp"
android:layout_marginRight="6dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_marginBottom="2dp"
android:textStyle="bold"
android:textColor="#color/colorFlLabelFinal"
android:textAppearance="?android:attr/textAppearanceLarge"
android:clickable="false"
android:layout_centerHorizontal="true" />
<Spinner
android:id="#+id/skycard_filter2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/Base.Widget.AppCompat.Spinner" />
**strong text**<android.support.v7.widget.CardView**strong text**
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
**strong text**android:id="#+id/detsinglecard_view"**strong text**
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
card_view:cardBackgroundColor="#android:color/white"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="4dp"
android:longClickable="true" >
...

You have to call setContentView() in onCreate() before accessing elements via findViewById()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
CardView cardView = (CardView) findViewById(detsinglecard_view);
cardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Bundle bundle2 = new Bundle();
bundle2.putInt("itemPosition",position);
android.app.FragmentManager fm = getFragmentManager();
DeleteCardViewFragment delCardViewDialog = new DeleteCardViewFragment();
delCardViewDialog.setArguments(bundle2);
delCardViewDialog.show(fm,"delcardview dialog");
return true;
}
}
}

Related

setOnItemClickListener not making any action on click in fragment

I have set this setOnItemClickListener() for the listview. However, when I press the list item, it doesn't do anything. I have already gone through all of the same questions on StackOverflow and none of them answers my question. However, the context menu appears fine when I long pressed the list item.
My code:
public class FragmentText extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int TEXT_LOADER = 0;
View textView;
FloatingActionButton fabText;
TextAdapter mTextAdapter;
ListView editorList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
t extView = inflater.inflate(R.layout.text_fragment, container, false);
fabText = textView.findViewById(R.id.add_text);
editorList = (ListView)textView.findViewById(R.id.editor_list);
fabText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent editorIntent = new Intent(textView.getContext(), TextEditor.class);
startActivity(editorIntent);
}
});
mTextAdapter = new TextAdapter(textView.getContext(), null);
editorList.setAdapter(mTextAdapter);
registerForContextMenu(editorList);
editorList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
}
});
getLoaderManager().initLoader(TEXT_LOADER, null, this);
return textView;
}
xml for listview:
<?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">
<ListView
android:id="#+id/editor_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/transparent" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/add_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="20dp"
android:src="#drawable/text"/>
</RelativeLayout>
xml code for list item:
<?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"
xmlns:tools="http://schemas.android.com/tools">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_margin="3dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="2dp"
android:longClickable="true"
android:foreground="?android:attr/selectableItemBackground">
<FrameLayout
android:background="#color/colorPrimaryDark"
android:layout_width="3dp"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/editor_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="About panda"
android:textSize="20sp"
android:layout_gravity="center_vertical"
android:paddingLeft="8dp"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
Use
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
Instead of
Toast.makeText(getContext(), "Clicked", Toast.LENGTH_SHORT).show();
For reference:
https://stackoverflow.com/a/32227421/5348018

When I press the button inside cardview, both cardview item and button is clicked

I have a Cardview with Button
card view layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
card_view:cardCornerRadius="3dp"
card_view:cardElevation="0.01dp"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="123dp"
android:background="#drawable/posts_card_bg"
android:orientation="horizontal"
android:paddingBottom="3dp"
android:paddingRight="3dp"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="0.8"
>
<TextView
android:id="#+id/post_title"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:alpha="1"
android:gravity="center_vertical"
android:maxLines="2"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="title"
android:textSize="30sp"/>
<TextView
android:id="#+id/post_body"
android:layout_width="match_parent"
android:textColor="#android:color/white"
android:layout_height="wrap_content"
android:maxLines="2"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="Body"
android:textSize="20sp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="120dp"
>
<Button
android:id="#+id/expand"
android:layout_width="40dp"
android:layout_height="37dp"
android:background="#drawable/expand"
/>
<TextView
android:id="#+id/post_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/circle"
android:gravity="center"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="99"
android:textColor="#android:color/white"
android:textSize="16sp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
PostCardAdapter.java
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
......
holder.btn_expand.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//for showing details of item on dialog
listener.onItemClicked(view);
}
});
}
Recyclerview item click
listener = this;
mRecyclerView = (RecyclerView) findViewById(R.id.cardlist_posts);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(new PostCardAdapter(listener,db.getAllPosts(), R.layout.cardview_post));
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int id) {
// TODO Handle item click
Intent intent = new Intent(MainActivity.this, ShowPostDetails.class);
intent.putExtra("KEY_POST_ID", String.valueOf(id + 1));
System.out.println(String.valueOf(id + 1));
//Starting another activity to show post details
startActivity(intent);
}
})
);
MainActivity.java
#Override
public void onItemClicked(View v) {
DialogPostFragment df= new DialogPostFragment();
df.show(getFragmentManager(), "Dialog");
}
When the button is pressed then the cardview item is clicked and ongoing back dialog is also opened.
I want to open dialog only when I press the button.
Thank You.
I had faced exactly the same issue once.This is how I solved it :
add id to the first linear layout inside the cardview :
<LinearLayout
android:id="#+id/rowLL"
android:layout_width="fill_parent"
android:layout_height="123dp"
android:background="#drawable/posts_card_bg"
android:orientation="horizontal"
android:paddingBottom="3dp"
android:paddingRight="3dp"
>
Now,in your PostCardAdapter.java :
public class PostCardAdapter extends RecyclerView
.Adapter<ContactViewHolder> {
...
private static MyClickListener myClickListener;
...
public void setOnItemClickListener(MyClickListener myClickListener) {
PostCardAdapter.myClickListener = myClickListener;
}
...
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
Then,in your ContactViewHolder.java
public class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private PostCardAdapter.MyClickListener myClickListener;
...
public ContactViewHolder(final Context context, View itemView, PostCardAdapter.MyClickListener clickListener) {
super(itemView);
...
myClickListener = clickListener;
itemView.findViewById(R.id.rowLL).setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getLayoutPosition(), v);
}
}

ViewPager in Custom Dialog

I have custom dialog to show which has instruction about how to use the app.I am using ViewPager for this inside my custom dialog layout.
I am getting error
java.lang.IllegalArgumentException: No view found for id for fragment FragmentForInstruction1.
I have created a method which is called in onCreate(Bundle savedInstanceState) {} method .The method inflates the layout for dialog.
private void showCustomDialogForInstruction() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogLayout = inflater.inflate(R.layout.dialog_layout_for_instruction_message, null, false);
layout.setAlpha(0.2f);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(dialogLayout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
ViewPager viewPager=(ViewPager) dialog.findViewById(R.id.pagerInstruction);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentForInstruction1());
adapter.addFrag(new Fragme`enter code here`ntForWelcomePage2());
adapter.addFrag(new FragmentForWelcomePage3());
adapter.addFrag(new FragmentForWelcomePage4());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageSelected(int pos)
{
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0)
{
}
});
Button done = (Button) dialog.findViewById(R.id.done);
done.setText("Got It");
done.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
Button neverShow = (Button) dialog.findViewById(R.id.nevershow);
neverShow.setText("Never Show Again");
neverShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return false;
}
});
dialog.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
my view pager class:
public class ViewPagerAdapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragmentList = new ArrayList<Fragment>();
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public Fragment getItem(int position)
{
return mFragmentList.get(position);
}
#Override
public int getCount()
{
return mFragmentList.size();
}
public void addFrag(Fragment fragment)
{
mFragmentList.add(fragment);
}
}
and i call the method in MainActivity :
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferencesNeverShowAgain ;
boolean neverShowAgain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferencesNeverShowAgain = PreferenceManager.getDefaultSharedPreferences(this);
neverShowAgain = sharedPreferencesNeverShowAgain.getBoolean("NeverShowAgain", false);
if(!neverShowAgain){
showCustomDialogForMessage();
}
}
}
and the layout for dialog is:
<?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="wrap_content"
android:background="#drawable/dialog_shape"
android:orientation="vertical" >
<!-- layout title -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#00000000"
android:gravity="center"
android:orientation="vertical" >
<ViewFlipper
android:id="#+id/flipper"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/top_edge_rounded"
android:flipInterval="2000"
android:padding="20dp" >
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:gravity="center"
android:text="Input Height"
android:textColor="#color/textColor"
android:textStyle="normal" />
<TextView
android:id="#+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:gravity="center"
android:text="Input Height"
android:textColor="#color/accent"
android:textStyle="normal" />
</ViewFlipper>
<View
android:id="#+id/tri"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/triangle"
android:rotation="180" />
</LinearLayout>
<!-- layout dialog content -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="300dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<android.support.v4.view.ViewPager
android:id="#+id/pagerInstruction"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/layoutIndicater"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
</ScrollView>
<!-- layout dialog buttons -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="10dp"
android:background="#drawable/all_rounded_edge_plum_for_dialog" >
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentTop="true"
android:background="#color/textColor" />
<View
android:id="#+id/ViewColorPickerHelper"
android:layout_width="1dp"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#color/textColor" />
<Button
android:id="#+id/nevershow"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/ViewColorPickerHelper"
android:background="?android:attr/selectableItemBackground"
android:padding="5dp"
android:text="Close"
android:textColor="#color/textColor" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_toRightOf="#id/ViewColorPickerHelper"
android:background="?android:attr/selectableItemBackground"
android:padding="5dp"
android:text="Done"
android:textColor="#color/textColor" />
</RelativeLayout>
</LinearLayout>
FragmentForInstruction1 code:
public class FragmentForInstruction1 extends Fragment{
#Override
#Nullable
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragmentinstructionpage1, container,false);
return view;
}
}
and its layout is:
<?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:background="#color/backgroundColor"
android:gravity="center" >
<TextView
android:id="#+id/titleWelcomeFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="30sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/messageWelcomeFragment1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textSize="20sp"
android:textStyle="normal"
android:paddingLeft="20dp"
android:paddingRight="20dp"/>
</LinearLayout>
You should create an adapter that extends FragmentPagerAdapter:
private class CustomPagerAdapter extends FragmentPagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentForInstruction1();
case 1:
return new FragmentForInstruction2();
case 2:
return new FragmentForInstruction3();
case 3:
return new FragmentForInstruction4();
default:
return new FragmentForInstruction1();
}
}
#Override
public int getCount() {
return 4;
}
}
While crating an instance of it, pass the getChildFragmentManager() instead of getSupportFragmentManager():
viewPager.setAdapter(new CustomPagerAdapter(getChildFragmentManager()));

Snackbar displaying on top of Fragment Fab button

I have activity with Textview and below viewpager. In one of the fragments of view pager, I have a fab button. When I am calling the Snackbar on Menu click of Activity, the Snackbar is coming over the fab button. Every thing works fine (fab button is pushed over snack bar) , if the fab button is in activity, but i need it fragment. Please let me know where I am doing mistake
Fragment Layout
<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/coordLayoutComments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/mdtp_white"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/rvComments"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabComments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginBottom="#dimen/btn_fab_margins"
android:layout_marginRight="#dimen/btn_fab_margins"
android:elevation="6dp"
android:src="#drawable/ic_comment_24_5"
app:borderWidth="0dp"
app:fabSize="mini"
app:pressedTranslationZ="12dp" />
</android.support.design.widget.CoordinatorLayout>
Activity Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="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.support.design.widget.CoordinatorLayout
android:id="#+id/coordLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include
android:id="#+id/newtoolbar"
layout="#layout/toolbar" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="120dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="2dp"
card_view:contentPadding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tvTitle"
fontPath="fonts/SourceSansPro-Regular.otf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ellipsize="end"
android:textSize="28sp" />
<TextView
android:id="#+id/tvDesc"
fontPath="fonts/Roboto-Italic.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:textSize="15sp"
android:textStyle="normal|italic"
tools:ignore="MissingPrefix" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/newtoolbar"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:scrollbars="horizontal" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
In you xml layout, there are two CoordinatorLayouts. One in Activity Layout and the other one in Fragment Layout. Now Snackbar.make() function's first argument is the parent Coordinator Layout in which this Snackbar will be placed, and all the elements of this Coordinator Layout will be affected by the motion/view changes of the Sanckbar. Try and use Fragment Layout's Coordinator Layout as the parent of the Snackbar.
Activity Code
public class HomeActivity extends AppCompatActivity
implements FragmentListener {
private LoadingDialog loadingDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HomeActivity.this.showSnackbar(view, "Replace with your own action");
}
});
}
#Override
public void showSnackBar(View view, String message) {
Snackbar.make(view,message,Snackbar.LENGTH_LONG).show();
}
}
FragmentListener Code
public interface FragmentListener {
void showSnackBar(View view,String message);
}
Fragment Code
public class MyFragment extends Fragment {
private static final String TAG = MyFragment.class.getSimpleName();
private FragmentListener fragmentListener;
private FloatingActionButton floatingActionButton;
public MyFragment() {
// Required empty public constructor
}
public static MyFragment getInstance(String uniqueId) {
MyFragment MyFragment = new MyFragment();
return MyFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_surveys, container, false);
floatingActionButton = view.findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragmentListner.showSnackBar(floatingActionButton,"hello");
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
fragmentListener = (FragmentListener) context;
} catch (Exception e) {
throw new ClassCastException(" must implement OnListItemSelectedListener");
}
}
}
For displaying the Snackbar in Activity and Fragment with FAB you can use this simple approach.
Activity and Fragment parent View should be CoordinatorLayout.
Create FragmentListener and implement in Activity

Code optimisation. (Architecture)

I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
The question is: how to optimize my code, I don't like how it's look like? If I decide to add some more options it wouldn't be readable.
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString().toLowerCase();
String t2 = et_one_two.getText().toString().toLowerCase();
String t3 = et_one_three.getText().toString().toLowerCase();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
});
}
}
In my Layout I use ScrollView:
<LinearLayout 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" tools:context=".MainActivity"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/task1"
android:id="#+id/textView1"
android:textSize="20sp"
android:textColor="#010101" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_one"
android:id="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_one"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_two"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_two"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_three"
android:id="#+id/textView4" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_three"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_four"
android:id="#+id/textView5" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_four"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_five"
android:id="#+id/textView6" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_five"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/buttonCheck" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
I would strongly suggest a nice library called Butterknife by JakeWharton :
http://jakewharton.github.io/butterknife/
In your case your code would look like this :
public class MainActivity extends AppCompatActivity {
#Bind(R.id.et_one_one) EditText et_one_one;
#Bind(R.id.et_one_two) EditText et_one_two;
#Bind(R.id.et_one_three) EditText et_one_three;
#Bind(R.id.buttonCheck) Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
...
}
#OnClick(R.id.submit)
public void submit(View view) {
// check code here
}
Also you can group all your edit texts in a group :
#Bind({ R.id.et_one_one, R.id.et_one_two, R.id.et_one_three })
List<EditText> nameViews;
And apply some setters or actions on them :
...
ButterKnife.apply(nameViews, LOWERCASE);
...
static final ButterKnife.Action<View> LOWERCASE= new ButterKnife.Action<View>() {
#Override public void apply(View view, int index) {
// TODO set the text of the view to lowercase and disable textview
}
};
You can use RecyclerView to implement this. With it, you can dynamically add as much EditText for cars as you want. The sample is shown as below:
In your Activity:
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] answerArray;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
answerArray = new String[]{
"maserati",
"mercedes",
"bmw"
... (you can add as much as you want)
}
buttonCheck = (Button) findViewById(R.id.buttonCheck);
}
For RecyclerView.Adapter
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
String[] mAnswerArray;
public static class ViewHolder extends RecyclerView.ViewHolder {
public EditText editText;
public ViewHolder(View v) {
super(v);
editText = (EditText) v.findViewById(R.id.editText);
}
}
public MyRecyclerAdapter(String[] answerArray) {
this.mAnswerArray = answerArray;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position){
super.onBindViewHolder(holder, position);
final String answer = mAnswerArray.get(position);
if ( holder.editText.getText().toString().toLowerCase().equals(answer) ) {
holder.editText.setBackgroundColor(Color.GREEN);
} else {
holder.editText.setBackgroundColor(Color.RED);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemCount() {
return mAnswerArray.size();
}
}
For "my_list_item.xml", you just need to put inside and as for the ButtonCheck you can also pass an array or flag into adapter to record the state of each answer (correct or wrong) in order to decide whether to go to SecondActivity.

Categories

Resources