My problem is I can not add text inside of recycleview after pressing the OK button unless i restart the app , every time I am writing a word inside of dialog box then press OK but the word does not appear inside of recycleview only after restart the app ,I want to type the word and then press the OK button Then the word appears directly inside the recycleview
// class Tab1 :
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import static android.R.attr.fragment;
import static com.example.chirag.slidingtabsusingviewpager.R.id.parent;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Tab1#newInstance} factory method to
* create an instance of this fragment.
*/
public class Tab1 extends Fragment {
#Inject
Context mContext_;
View rootView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Context context;
SimpleAdapter adapter;// = new SimpleAdapter(generateSimpleList());
RecyclerView recyclerView ;//= (RecyclerView) view.findViewById(R.id.simple_recyclerview);
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private List<Organization>organizationList;
private OnFragmentInteractionListener mListener;
private static Context mContext;
LayoutInflater inflater2;
ViewGroup Container = null;
View vr;
public Tab1(){
// Required empty public constructor
// test ();
//context = getContext();
Organization organization = new Organization();
organizationList = SQLite.select().from(Organization.class).queryList();
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Tab1.
*/
// TODO: Rename and change types and number of parameters
public static Tab1 newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_tab1, container,false);
vr = view;//inflater.inflate(R.layout.fragment_tab1, container,false);
initViews();
showInputDialog();
return view;
}
private void initViews(){
adapter = new SimpleAdapter(generateSimpleList());
recyclerView = (RecyclerView)vr.findViewById(R.id.simple_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + "must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private List<SimpleViewModel> generateSimpleList(){
List<SimpleViewModel>simpleViewModelList = new ArrayList<>();
for(int i=0; i<organizationList.size(); i++){
simpleViewModelList.add(new SimpleViewModel(String.format(Locale.US,organizationList.get(i).getName().toString(),""+organizationList.get(i).getName().toString())));
// Toast.makeText(MainActivity.this,"as"+ organizationList.get(i).getName(), Toast.LENGTH_LONG).show();
}
return simpleViewModelList;
}
protected void showInputDialog(){
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
//LayoutInflater layoutInflater = LayoutInflater.from(getContext().getApplicationContext());
final View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false).setPositiveButton("OK",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Organization organization = new Organization();
organization.setId(organizationList.size()+1);
organization.setName(editText.getText().toString());
organization.save();
//initViews();
}}).setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
//create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
/*
AlertDialog alert = alertDialogBuilder.create();
alert.show();
*/
}
}
/
/Organization class :
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
// **Note:** Your class must extend from BaseModel
#Table(database = MyDatabase.class)
public class Organization extends BaseModel {
#Column
#PrimaryKey
int id;
#Column
String name;
private Organization organization;
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public void setName(String name) {
this.name = name;
}
}
// input_dialog.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="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enter Name"
android:id="#+id/textView"/>
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter text here.."
android:padding="10dp"/>
</LinearLayout>
After you have changed the data you need to call notifyDataSetChanged() on your Adapter in order to update the data in your RecycleView.
Set this wherever you make changes to the source data:
adapter.notifyDataSetChanged()
Note: As a precaution you might want to check that "adapter" is not null.
Add these two lines, inside your onClick of setPositiveButton
(Just after organization.save())
.......
organization.save();
organizationList.add(organization);
adapter.notifyDataSetChanged();
Related
Wanna make to search with using EditText when I click it from ListView. I made it with some youtube videos or blogs. Mixed up those and of course, There's error. What should fix? I put my every codes to understand it. Need you guys help a lot.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".Playbook">
<ListView
android:id="#+id/listView2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_baseline_search_24"
android:id="#+id/searchImage" />
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="#id/searchImage"
android:id="#+id/editTextFilter"/>
<TextView
android:id="#+id/termName"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editTextFilter"
style="#style/TextAppearance.AppCompat.Title"
android:text="Term"/>
</RelativeLayout>
This is layout part.
package com.example.gridiron;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Playbook#newInstance} factory method to
* create an instance of this fragment.
*/
public class Playbook extends Fragment {
ArrayList<PlaybookList> arrayList2;
ListView listView2;
private static PlaybookListAdapter playbookListAdapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Playbook() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Playbook.
*/
// TODO: Rename and change types and number of parameters
public static Playbook newInstance(String param1, String param2) {
Playbook fragment = new Playbook();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_playbook, container, false);
ListView listView2 = (ListView) view.findViewById(R.id.listView2);
EditText editTextFilter = (EditText) view.findViewById(R.id.editTextFilter);
ArrayList<PlaybookList> arrayList2 = new ArrayList<>();
arrayList2.add(new PlaybookList("Quarterback", "https://namu.wiki/w/%EC%BF%BC%ED%84%B0%EB%B0%B1"));
arrayList2.add(new PlaybookList("Runningback", "https://namu.wiki/w/%EB%9F%AC%EB%8B%9D%EB%B0%B1"));
PlaybookListAdapter playbookListAdapter = new PlaybookListAdapter(getActivity(), R.layout.list_row2, arrayList2);
listView2.setAdapter(playbookListAdapter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable edit) {
String filterText = edit.toString();
if (filterText.length() > 0) {
listView2.setFilterText(filterText);
} else {
listView2.clearTextFilter();
}
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList2.get(position).getTermURL())));
getActivity().startActivity(intent);
}
});
return view;
}
}
package com.example.gridiron;
public class PlaybookList {
String TermName;
String TermURL;
public PlaybookList(String termName, String termURL) {
TermName = termName;
TermURL = termURL;
}
public String getTermName() {
return TermName;
}
public void setTermName(String termName) {
TermName = termName;
}
public String getTermURL() {
return TermURL;
}
public void setTermURL(String termURL) {
TermURL = termURL;
}
}
package com.example.gridiron;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class PlaybookListAdapter extends ArrayAdapter<PlaybookList> {
private Context mContext;
private int mResource;
public PlaybookListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<PlaybookList> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
TextView termName = convertView.findViewById(R.id.termName);
termName.setText(getItem(position).getTermName());
return convertView;
}
}
And last 3 codes are for class. It's really hard to make it. Please, Help me!
There is no ListView in your layout code. You didn't include the error but I'm pretty sure it's NullPointerException on this line:
listView2.setAdapter(playbookListAdapter);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to put my NestedScrollView on my MapFragment, but when I'm trying to, this error appears :
Attempt to invoke virtual method 'android.view.View android.support.v4.widget.NestedScrollView.findViewById(int)' on a null object reference
Here is my MapFragment.java file
package com.example.alexandre.list.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.alexandre.list.MainActivity;
import com.example.alexandre.list.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link OnMapClickListener} interface
* to handle interaction events.
* Use the {#link MapFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GoogleMap mGoogleMap;
private MapView mMapView;
private OnMapClickListener mListener;
public MapFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MapFragment.
*/
// TODO: Rename and change types and number of parameters
public static MapFragment newInstance(String param1, String param2) {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_map, container, false);
bindViews(view, savedInstanceState);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed() {
if (mListener != null) {
mListener.onMapClick();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMapClickListener) {
mListener = (OnMapClickListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnTweetListClickListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void bindViews(View view, Bundle savedInstanceState) {
mMapView = view.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
LatLng castlePos = new LatLng(45.209299, 5.659144);
LatLng treePos = new LatLng(MainActivity.posx, MainActivity.posy);
CameraPosition liberty = CameraPosition.builder().target(castlePos).zoom(17)/*.bearing(0).tilt(0)*/.build();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(treePos)
.title("Test du cèdre du Liban")
.snippet("Libani"));
marker.hideInfoWindow();
mGoogleMap.setOnMarkerClickListener(
new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
NestedScrollView nestedScrollView = null;
nestedScrollView = (NestedScrollView) nestedScrollView.findViewById(R.id.bottom_sheet);
nestedScrollView.setVisibility(View.VISIBLE);
return false;
}
}
);
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(liberty));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnMapClickListener {
void onMapClick();
}
}
It looks like R.id.nestedScrollView return NULL, but why ?
Thanks !
Move this code NestedScrollView nestedScrollView; to the top, and reference it in your onCreateView() method. Like this:
nestedScrollView = (NestedScrollView) view.findViewById(R.id.bottom_sheet);. Now you can use it in any method in the fragment including your onMarkerClick().
You're getting the NPE error because your code is telling the Dalvik Machine that it should look for NestedScrollView in a null view NestedScrollView nestedScrollView= null.
Hope it helps.
<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="wrap_content"
android:orientation="vertical"
tools:context="mcb.myclickbazaar.Fragments.DateTimePlace">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false"
android:fillViewport="true"
android:padding="10dp">
<LinearLayout>
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
</LinearLayout>
</ScrollView>
</RelativeLayout>
The scrollview is not working. I have tried all the answers from stackoverflow, but still can't find a way to solve this issue.
This xml file is a fragment. It is one of the fragment from tabbedView Activity.
EDIT
JAVA FILE
package mcb.myclickbazaar.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import mcb.myclickbazaar.Fragments.DateTimePlace;
import mcb.myclickbazaar.Fragments.FinalBill;
import mcb.myclickbazaar.Fragments.ItemSelect;
import mcb.myclickbazaar.R;
public class ProceedingsActivity extends AppCompatActivity implements ItemSelect.OnFragmentInteractionListener,
DateTimePlace.OnFragmentInteractionListener,FinalBill.OnFragmentInteractionListener{
private static final String TAG = "ProceedingsActivity";
private ViewPager mViewPager;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proceedings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
viewPager = (ViewPager) findViewById(R.id.viewpager_proceedings);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#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_proceedings, 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);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ItemSelect(), "Select");
adapter.addFragment(new DateTimePlace(), "DateTime");
adapter.addFragment(new FinalBill(), "Bill");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentInteraction(Uri uri) {
Log.e(TAG,"Working: on onFragmentInteraction");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment Code
package mcb.myclickbazaar.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import mcb.myclickbazaar.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link DateTimePlace.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link DateTimePlace#newInstance} factory method to
* create an instance of this fragment.
*/
public class DateTimePlace extends Fragment implements AdapterView.OnItemSelectedListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String upcoming_date_1,upcoming_date_2,upcoming_date_3,upcoming_date_4;
private EditText editText_date;
private EditText editText_time;
private Spinner spinner_calendar;
private Spinner spinner_time;
private OnFragmentInteractionListener mListener;
public DateTimePlace() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment DateTimePlace.
*/
// TODO: Rename and change types and number of parameters
public static DateTimePlace newInstance(String param1, String param2) {
DateTimePlace fragment = new DateTimePlace();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// Spinner element
final View view = inflater.inflate(R.layout.fragment_date_time_place, container, false);
spinner_calendar = (Spinner) view.findViewById(R.id.spinner_calender);
spinner_time = (Spinner) view.findViewById(R.id.spinner_time);
editText_date = (EditText) view.findViewById(R.id.editText_SelectDate_DTP);
editText_time = (EditText) view.findViewById(R.id.editText_SelectTime_DTP);
editText_date.setFocusable(false);
editText_time.setFocusable(false);
editText_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_calendar.setVisibility(View.VISIBLE);
spinner_calendar.performClick();
editText_date.setHint("");
}
});
editText_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_time.setVisibility(View.VISIBLE);
spinner_time.performClick();
editText_time.setHint("");
}
});
// Spinner click listener
spinner_calendar.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_calender = new ArrayList<String>();
categories_calender.add("Today");
categories_calender.add("Tomorrow");
categories_calender.add(getUpcoming_Date(2));
categories_calender.add(getUpcoming_Date(3));
categories_calender.add(getUpcoming_Date(4));
categories_calender.add(getUpcoming_Date(5));
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_calendar = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_calender);
// Drop down layout style - list view with radio button
dataAdapter_calendar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_calendar.setAdapter(dataAdapter_calendar);
// Spinner click listener
spinner_time.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_time = new ArrayList<String>();
categories_time.add("9AM - 11AM");
categories_time.add("11AM - 1PM");
categories_time.add("1PM - 3PM");
categories_time.add("3PM - 5PM");
categories_time.add("5PM - 7PM");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_time = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_time);
// Drop down layout style - list view with radio button
dataAdapter_time.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_time.setAdapter(dataAdapter_time);
return view;
}
private String getUpcoming_Date(int upcoming){
Calendar c = Calendar.getInstance();
Date dt = new Date();
c.add(Calendar.DATE, upcoming);
SimpleDateFormat df = new SimpleDateFormat("EEE,dd MMM", Locale.US);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
try this :
make hight match_parent for relativeLayout and ScrollView both like below
<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">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sdsd"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Keep scroll view height as match parent and the height of everything inside it as wrap content.
I've tried to set up a click and toch listener for my RecyclerView with tutorials. But every tutorial I've tried I finaly failed because I've set the RecyclerView up with an other tutorial and all tutorials are looking different. Please can you help me detect click for each row? For example when a user clicks my first row (which is a logout field) it should logout the user from the app. All of my logout actions are working but the click on RecyclerView don't.
My SettingsAdapter:
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Johannes on 19.01.2017.
*/
public class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.MySettingHolder> {
private List<Settings> settingList;
public class MySettingHolder extends RecyclerView.ViewHolder {
public ImageView settingImage;
public TextView settingTitle, settingSubtitle;
public MySettingHolder(View view) {
super(view);
settingImage = (ImageView) view.findViewById(R.id.settingImage);
settingTitle = (TextView) view.findViewById(R.id.settingTitle);
settingSubtitle = (TextView) view.findViewById(R.id.settingSubtitle);
}
}
public SettingsAdapter (List<Settings> settingList) {
this.settingList = settingList;
}
#Override
public MySettingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.settings_list_row, parent, false);
return new MySettingHolder(itemView);
}
#Override
public void onBindViewHolder(MySettingHolder holder, int position) {
// Setting for one entry
Settings setting = settingList.get(position);
holder.settingImage.setImageResource(setting.getSettingImageUrl());
// If the settingSubtitle is empty it should be not visible and just the settingTitle
if (setting.getSettingSubtitle().equals("")) {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setVisibility(View.GONE);
} else {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setText(setting.getSettingSubtitle());
}
}
#Override
public int getItemCount() {
return settingList.size();
}
}
This is my SettingsFragment where I implement the RecyclerView
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SettingsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SettingsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SettingsFragment extends Fragment {
// Variables
private OnFragmentInteractionListener mListener;
// Variables for Recycler View
private List<Settings> settingList = new ArrayList<>();
private RecyclerView accountRecyclerView;
private SettingsAdapter aAdapter;
public SettingsFragment() {
// Required empty public constructor
}
//Change the title in action bar
public void onResume(){
super.onResume();
String titleString = getResources().getString(R.string.title_activity_navigation_drawer_settings);
// Set title bar
((NavigationDrawerActivity) getActivity())
.setActionBarTitle(titleString);
}
public static SettingsFragment newInstance() {
SettingsFragment fragment = new SettingsFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
accountRecyclerView = (RecyclerView) view.findViewById(R.id.account_recycler_view);
aAdapter = new SettingsAdapter(settingList);
RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext()) {
// Disable scrolling in the RecyclerView
#Override
public boolean canScrollVertically() {
return false;
}
};
// Setup account RecyclerView
accountRecyclerView.setLayoutManager(aLayoutManager);
accountRecyclerView.setItemAnimator(new DefaultItemAnimator());
prepareAccountData();
accountRecyclerView.setAdapter(aAdapter);
return view;
}
private void prepareAccountData() {
// Create new setting
Settings setting = new Settings(R.drawable.ic_menu_logout, "Abmelden", "Deine Daten bleibe erhalten");
// Add Object to list
settingList.add(setting);
// Notify data changes
aAdapter.notifyDataSetChanged();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
#Override
public void onBindViewHolder(MySettingHolder holder, int position) {
// Setting for one entry
Settings setting = settingList.get(position);
holder.settingImage.setImageResource(setting.getSettingImageUrl());
// If the settingSubtitle is empty it should be not visible and just the settingTitle
if (setting.getSettingSubtitle().equals("")) {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setVisibility(View.GONE);
} else {
holder.settingTitle.setText(setting.getSettingTitle());
holder.settingSubtitle.setText(setting.getSettingSubtitle());
}
holder.type = setting.getType();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySettingHolder holder = (MySettingHolder )(v.getTag());
switch (holder.type) {
case 1:
// do logout
break;
case 2:
// do other stuff
break;
default:
break;
}
}
});
// set viewholder
holder.itemView.setTag(holder);
}
Also remind to update your ViewHolder like this and to add a type variable into Settings.class
public class MySettingHolder extends RecyclerView.ViewHolder {
public int type;
public ImageView settingImage;
public TextView settingTitle, settingSubtitle;
public MySettingHolder(View view) {
super(view);
settingImage = (ImageView) view.findViewById(R.id.settingImage);
settingTitle = (TextView) view.findViewById(R.id.settingTitle);
settingSubtitle = (TextView) view.findViewById(R.id.settingSubtitle);
}
}
i've tried to add tabLayout in my application. When I open the fragment (where there is my tablayout) for the first time it works fine, but if I close the fragment and I try to re-open it, the tab indicator doesn't follow my swipe and all viewPager became blank... how can I resolve this problem?
my fragment:
package com.gabrielemarcozzi.mycal;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PercentageFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment PercentageFragment.
*/
// TODO: Rename and change types and number of parameters
public static PercentageFragment newInstance(String param1, String param2) {
PercentageFragment fragment = new PercentageFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public PercentageFragment() {
// Required empty public constructor
}
private FragmentActivity context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_percentage, container, false);
Toolbar mToolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.percentage);
ViewPager percentagePager = (ViewPager)view.findViewById(R.id.percentage_pager);
percentagePager.setAdapter(new PercentagePagerAdapter(context.getSupportFragmentManager()));
TabLayout percentageTab = (TabLayout)view.findViewById(R.id.percentage_tabs);
percentageTab.setupWithViewPager(percentagePager);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
MainActivity main = (MainActivity) activity;
mListener = main;
context = (FragmentActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
class PercentagePagerAdapter extends FragmentPagerAdapter {
String[] pergentageTabsArray;
public PercentagePagerAdapter(FragmentManager fm) {
super(fm);
pergentageTabsArray = getResources().getStringArray(R.array.percentage_tabs);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
TabsPercentageFragment TabsPercFrag = TabsPercentageFragment.getIstance(position);
return TabsPercFrag;
}
#Override
public CharSequence getPageTitle(int position) {
return pergentageTabsArray[position];
}
#Override
public int getCount() {
return 3;
}
}
public static class TabsPercentageFragment extends android.support.v4.app.Fragment {
public static TabsPercentageFragment getIstance(int position) {
TabsPercentageFragment increaseFrag = new TabsPercentageFragment();
Bundle args = new Bundle();
args.putInt("position", position);
increaseFrag.setArguments(args);
return increaseFrag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
Bundle bundle = getArguments();
switch(bundle.getInt("position")) {
case 1:
view = inflater.inflate(R.layout.fragment_discount, container, false);
break;
case 2:
view = inflater.inflate(R.layout.fragment_xofy, container, false);
break;
default:
view =inflater.inflate(R.layout.fragment_increase, container, false);
break;
}
return view;
}
}
}
my fragment xml file:
<LinearLayout
android:id="#+id/percentage_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.gabrielemarcozzi.mycal.PercentageFragment">
<android.support.design.widget.TabLayout
android:id="#+id/percentage_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorUp"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#color/colorUp"/>
<android.support.v4.view.ViewPager
android:id="#+id/percentage_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<!-- TODO: Update blank fragment layout -->
</LinearLayout>
Try to user getChildFragmentManager() instead of getSupportFragmentManager() at:
percentagePager.setAdapter(new PercentagePagerAdapter(context.getSupportFragmentManager()));
and change your import from:
import android.app.Fragment;
to
import android.support.v4.app.Fragment;