Change fragment from spinner in a top fragment - java

I've an app with a tab view, which has 2 tab. Tab 2 contains a spinner that has a drop-down function. The spinner includes Prova 1, 2, etc. Clicking on each item will open a fragment below. Clicking on the Prova 1, will take me to a page that show some information, but it doesn't work.
Picture 1
Picture 2
Picture 3
FragmentTop.java
public class FragmentTop extends Fragment { //implements AdapterView.OnItemClickListener{
// 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";
private Spinner spinner;
private String[] items;
private FragmentProva1 fragmentProva1;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentTop() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static FragmentTop newInstance(String param1, String param2) {
FragmentTop fragment = new FragmentTop();
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_Top, container, false);
items = getResources().getStringArray(R.array.Top);
fragmentProva1 = new FragmentProva1();
spinner = view.findViewById(R.id.spinnerTop);
initSpinner();
// Inflate the layout for this fragment
return view;
}
private void initSpinner() {
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = adapterView.getItemAtPosition(i).toString();
switch (text){
case "Prova1":
setFragment(fragmentProva1);
break;
case "Prova2":
break;
}
Toast.makeText(adapterView.getContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentTop_id, fragment);
fragmentTransaction.commit();
}
}
fragment_top.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentTop">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Spinner
android:id="#+id/spinnerTop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16sp"
android:textSize="16sp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentTop_id" />
</ScrollView>
</LinearLayout>
</FrameLayout>
FragmentProva1.java
public class FragmentProva1 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";
private TextInputLayout textInputSideA;
private TextInputLayout textInputSideB;
private TextInputLayout textInputSideC;
private TextView result;
private Button btnCalculate;
private LinearLayout Prova1LinearLayout;
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentProva1() {
// Required empty public constructor
}
public static FragmentProva1 newInstance(String param1, String param2) {
FragmentProva1 fragment = new FragmentProva1();
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_prova1, container, false);
textInputSideA = view.findViewById(R.id.textInputSideA);
textInputSideB = view.findViewById(R.id.textInputSideB);
textInputSideC = view.findViewById(R.id.textInputSideC);
result = view.findViewById(R.id.result);
Prova1LinearLayout = view.findViewById(R.id.Prova1LinearLayout);
btnCalculate = view.findViewById(R.id.btnCalculate);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double info1;
double info2;
double info3;
if(!validateLatoA() | !validateLatoB() | !validateLatoC()){
return;
}
info1 = calculate();
}
});
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(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;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private boolean validateLatoA(){
String latoA_Input = textInputSideA.getEditText().getText().toString().trim();
if(latoA_Input.isEmpty()){
textInputSideA.setError("Field can't be empty");
return false;
} else {
textInputSideA.setError(null);
return true;
}
}
private boolean validateLatoB(){
String latoB_Input = textInputSideB.getEditText().getText().toString().trim();
if(latoB_Input.isEmpty()){
textInputSideB.setError("Field can't be empty");
return false;
} else {
textInputSideB.setError(null);
return true;
}
}
private boolean validateLatoC(){
String latoC_Input = textInputSideC.getEditText().getText().toString().trim();
if(latoC_Input.isEmpty()){
textInputSideC.setError("Field can't be empty");
return false;
} else {
textInputSideC.setError(null);
return true;
}
}
}
fragment_prova1.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentProva1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="UselessParent"
android:padding="16sp"
android:layout_marginTop="16sp"
android:id="#+id/Prova1LinearLayout">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info1"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info2"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputSideC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="info3"
android:textSize="16sp"
android:inputType="numberDecimal"/>
</com.google.android.material.textfield.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate"
android:textSize="16sp"
android:id="#+id/btnCalculate"/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="16sp"
android:padding="16dp"/>
</LinearLayout>
</FrameLayout>

Related

I get an error in the button click listener (Android Studio)

I made an app to send mail separately and I am trying to implement it within another app, well it gives me this error Attempt to invoke virtual method
'void android.widget.Button.setOnClickListener (android.view.View $ OnClickListener)' on a null object reference
I have the id well that I know and the way to put the button and the click listener are well located. What can the error give?
this is my code
public class ContactFragment extends Fragment {
//public EditText mEmail;
public EditText mSubject;
public EditText mMessage;
private Button buttonSend_contact;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public ContactFragment() {
}
public static ContactFragment newInstance(String param1, String param2) {
ContactFragment fragment = new ContactFragment();
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_videos, container, false);
mMessage = view.findViewById(R.id.messageID);
mSubject = view.findViewById(R.id.subjectID);
buttonSend_contact = view.findViewById(R.id.buttonSendMail);
buttonSend_contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMail();
}
});
return view;
}
private void sendMail() {
String mail = "turespawnofficial#gmail.com";
String message = mMessage.getText().toString();
String subject = mSubject.getText().toString().trim();
//Send Mail
JavaMailAPI javaMailAPI = new JavaMailAPI(getActivity(),mail,subject,message);
javaMailAPI.execute();
}
this is my xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".ContactFragment">
<!-- <EditText
android:id="#+id/mailID"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"/> -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/subjectID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Subject" />
<EditText
android:id="#+id/messageID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Message" />
<Button
android:id="#+id/buttonSendMail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</FrameLayout>

Button doesn't work when adding to fragment

I have a button in an fragment that when I clicked on it nothing happens at all
this is the java code of the fragment:
public class HomeFragment 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;
EditText etAddPost;
Button addPostImage;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef;
public HomeFragment() {
// 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 HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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);
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
etAddPost =rootView.findViewById(R.id.etAddPost);
addPostImage = rootView.findViewById(R.id.addPostBtn);
addPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
String postText = etAddPost.getText().toString();
if(TextUtils.isEmpty(postText)){
etAddPost.setError("لا يمكنك ترك هذا الحقل فارغا");
}
else {
Map<String, String> map = new HashMap<>();
map.put("postContent", postText);
myRef.push().setValue(map);
etAddPost.setText("");
}
}
}); return rootView;
}
// 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;
}
"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);
}
}
and this is my XML code :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="#color/color3"
tools:context="com.mk.playAndLearn.fragment.HomeFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<Button
android:id="#+id/addPostBtn"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#drawable/send"
android:layout_marginRight="5dp"/>
<EditText
android:layout_margin="5dp"
android:id="#+id/etAddPost"
android:layout_width="0dp"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_weight="7"
android:hint="ماذا يخطر في بالك؟"
android:paddingRight="10dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
I have tried a lot to solve this problem but I couldn't but I am feeling that solving the problem is easy so I hope that any one helps me to solve this problem I tried to change the button type and use ImageButton instead but that doesn't solve the problem
I think you've problems with xml layout. Your recyclerview laying over linear layout. Change the layout as below
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="#color/color3"
tools:context="com.mk.playAndLearn.fragment.HomeFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal">
<Button
android:id="#+id/addPostBtn"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#drawable/send"
android:layout_marginRight="5dp"/>
<EditText
android:layout_margin="5dp"
android:id="#+id/etAddPost"
android:layout_width="0dp"
android:gravity="right"
android:layout_height="wrap_content"
android:layout_weight="7"
android:hint="ماذا يخطر في بالك؟"
android:paddingRight="10dp"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</FrameLayout>

No adapter attached; skipping layout ,while displaying a list using recycler VIew

I know this question was asked before but even after looking for all the answer
I couldn't find anything relevant. I am basically trying to display a list of items inside a fragment using recycler view, but it saysNo adapter attached; skipping layout even though I have attached an adapter.
Note: I am using a Tab Layout where there are three tabs and a fragment inside each Tab. I am trying to display the recycler view list in one of the fragment.
Here is my Adapter class:
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongViewHolder> {
ArrayList<SongData> songList;
public SongAdapter(ArrayList songList) {
this.songList = songList;
}
//Getting hold of each item of the RecyclerView
public static class SongViewHolder extends RecyclerView.ViewHolder {
ImageView albumArt;
TextView Title,Artist;
public SongViewHolder(View itemView) {
super(itemView);
albumArt = (ImageView)itemView.findViewById(R.id.AlbumImage);
Title= (TextView)itemView.findViewById(R.id.Title);
Artist = (TextView)itemView.findViewById(R.id.Artist);
}
}
#Override
public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.music_tiles,parent,false);
SongViewHolder svh= new SongViewHolder(view);
return svh;
}
#Override
public void onBindViewHolder(SongViewHolder holder, int position) {
SongData songData = songList.get(position);
holder.Title.setText(songData.Title);
holder.Artist.setText(songData.Artist);
holder.albumArt.setImageResource(songData.ImageId);
}
#Override
public int getItemCount() {
return songList.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Fragment code:
public class musicFrag 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;
public musicFrag() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static musicFrag newInstance(String param1, String param2) {
musicFrag fragment = new musicFrag();
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_music, container, false);
//Initializing RecyclerView , SongAdapter, LinerLayoutManager
SongData songData =new SongData();
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager( new LinearLayoutManager(getActivity()));
SongAdapter songAdapter = new SongAdapter(songData.InitializeData());
recyclerView.setAdapter(songAdapter);
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(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;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Fragment layout:
<android.support.constraint.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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.dannproductions.musify.MainActivity$PlaceholderFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
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" />
</android.support.constraint.ConstraintLayout>
SongData Class :
public class SongData {
String Title,Artist;
int ImageId;
public SongData() {
};
public SongData(String title, String Artist, int ImageId) {
this.Title = Title;
this.Artist = Artist;
this.ImageId = ImageId;
}
ArrayList<SongData> songList;
public ArrayList<SongData> InitializeData(){
songList = new ArrayList<SongData>();
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
songList.add(new SongData("Aman","Chatterjee",R.drawable.round));
return songList;
}
}
Here is the RecyclerView item layout:
<?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">
<android.support.v7.widget.CardView
android:id="#+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/AlbumImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginEnd="10dp"
android:src="#drawable/round"
app:civ_border_color="#d35400"
app:civ_border_width="4dp" />
<TextView
android:id="#+id/Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="30dp"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView"
android:textSize="25sp" />
<TextView
android:id="#+id/Artist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Title"
android:layout_centerHorizontal="true"
android:layout_toEndOf="#id/AlbumImage"
android:text="TextView" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
I pasted your adapter and recyclerview code in my android studio. and i found no bug in your list filling code. Here is how your list looks.
So double check your tablayout and fragment code if you are having some issue.

Manual swiping in view pager using Trinea/android-auto-scroll-view-pager is not working?

I am using third party library for automatic scrolling and touch events in an image slider every thing is working fine except manual swiping of images in image slider. I am not able to swipe images manually.
Name of the library which I am using is
"Trinea/android-auto-scroll-view-pager"
Here is my code for fragment where Ii am using auto scroll view pager:
public class HomeFragment 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";
TextView tv_slider, tv_button;
AutoScrollViewPager mViewPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
private static final Integer[] IMAGES= {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
private ArrayList<Integer> ImagesArray = new ArrayList<Integer>();
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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 v = inflater.inflate(R.layout.fragment_home, container, false);
tv_slider=(TextView)v.findViewById(R.id.tv_slider);
tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
tv_button=(TextView)v.findViewById(R.id.tv_button);
tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));
for(int i=0;i<IMAGES.length;i++)
ImagesArray.add(IMAGES[i]);
mViewPager = (AutoScrollViewPager) v.findViewById(R.id.pager);
mViewPager.setAdapter(new SlidingImage_Adapter(getActivity(),ImagesArray));
mViewPager.setOffscreenPageLimit(1);
CirclePageIndicator indicator = (CirclePageIndicator)
v.findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
final float density = getResources().getDisplayMetrics().density;
//Set circle indicator radius
indicator.setRadius(3 * density);
NUM_PAGES =IMAGES.length;
mViewPager.startAutoScroll();
mViewPager.setInterval(3000);
mViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch(motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
Log.w("touched","down");
mViewPager.stopAutoScroll();
return true;
//break;
case MotionEvent.ACTION_UP:
Log.w("touched","up");
mViewPager.startAutoScroll();
return true;
}
return true;
}
});
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
switch (pos){
case 0:
tv_slider.setText(getString(R.string.es_content));
break;
case 1:
tv_slider.setText(getString(R.string.dm_content));
break;
case 2:
tv_slider.setText(getString(R.string.ev_content));
break;
case 3:
tv_slider.setText(getString(R.string.it_content));
break;
case 4:
tv_slider.setText(getString(R.string.md_content));
break;
case 5:
tv_slider.setText(getString(R.string.seo_content));
break;
case 6:
tv_slider.setText(getString(R.string.sd_content));
break;
case 7:
tv_slider.setText(getString(R.string.wd_content));
break;
}
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
return v;
}
// 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 onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onResume() {
super.onResume();
mViewPager.startAutoScroll();
}
#Override
public void onStop() {
super.onStop();
mViewPager.stopAutoScroll();
}
}
This is my adapter class:
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
super();
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.sliding_images, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
This is homefragment.xml file
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/background"
tools:context="com.vamediabox.vamediaboxapp.activities.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/colorPrimary">
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
>
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/rl_slider"
android:gravity="center_horizontal"
app:cardUseCompatPadding="true"
app:cardElevation="4dp"
app:cardCornerRadius="3dp"
app:cardPreventCornerOverlap="false"
android:layout_centerHorizontal="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="2dp"
android:id="#+id/rl1">
<cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_margin="2dp"
android:layout_alignParentTop="true" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="20dp"
android:layout_centerHorizontal="true"
android:layout_below="#+id/pager"
android:padding="5dip"
app:centered="true"
app:fillColor="#color/colorPrimary"
app:pageColor="#color/view_color"
app:snap="false" />
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/tv_slider"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:textSize="14sp"
android:layout_below="#+id/indicator"
android:textColor="#color/slider_text"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
and last this is sliding_images.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY" />
</FrameLayout>
not sure if you still looking for a way to fix this in case you do, check consumeTouch inside AutoScrollViewPager this is where your issue is.
You need to make sure that
getParent().requestDisallowInterceptTouchEvent(true)
is getting called.
hope this helps.
Cheers

TabHost not working upon multiple Tab switches

i have made a Master/Detail View which contains a TabHost in the Detailview.
i have to populate a list of tabs, and every tab has a listview as its content.
Now when i change my Item to display, after the third change or so, no more tab content is rendered(The indicators are rendered). But when i change the tab, the content gets rendered.
The onCreate Method of the DetailFragment is invoked when i change my item to display. The tabs are genrated and added to the tabhost. But after a few times i switched the item to display, the onCreateView Method of the OrderGroupTabFragment is not invoked anymore, without any reason to me.
Thankful for any help.
Here is my code:
DetailFragment:
/**
* A fragment representing a single Order detail screen. This fragment is either
* contained in a {#link OrderListActivity} in two-pane mode (on tablets) or a
* {#link OrderDetailActivity} on handsets.
*/
public class OrderDetailFragment extends Fragment implements IASyncMethodCallbacks {
private static Logger _logger = Logger.getLogger(OrderDetailFragment.class.getSimpleName());
/**
* The fragment argument representing the item ID that this fragment
* represents.
*
*/
public static final String ARG_ORDER = "order";
private TrafficSafetyOrder _order;
private TrafficSafetyOrderService _trafficSafetyOrderService;
private boolean _detached;
private FragmentTabHost tabHost;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public OrderDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_detached = false;
_trafficSafetyOrderService = new TrafficSafetyOrderService();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_order_detail,
container, false);
tabHost = (FragmentTabHost)rootView.findViewById(R.id.order_detail_tab_host);
tabHost.setup(getActivity(), ((FragmentActivity)getActivity()).getSupportFragmentManager() , android.R.id.tabcontent);
OrderListItem order = (OrderListItem)getArguments().getSerializable(ARG_ORDER);
try {
if(order != null)
_order = _trafficSafetyOrderService.getOrderForId(order.getId());
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
if (_order != null) {
OrderId orderId = _order.getOrderIdByOrderIdType(OrderIdTypes.GEB);
((TextView) rootView.findViewById(R.id.order_detail_header))
.setText("Auftrag: " + orderId.getName() + orderId.getId());
for (final Group formGroup : _order.getFormGroups()) {
System.out.println("Adding Tab " + formGroup.getDisplayText());
TabSpec spec = tabHost.newTabSpec(formGroup.getDisplayText());
System.out.println("Spec created " + formGroup.getDisplayText());
spec.setIndicator(formGroup.getDisplayText());
System.out.println("Indicator set " + formGroup.getDisplayText());
Bundle bundle = new Bundle();
System.out.println("Bundle created " + formGroup.getDisplayText());
bundle.putSerializable(OrderGroupTabFragment.ORDER_GROUP_LIST_ARG, formGroup.getItems());
System.out.println("Added items to bundle " + formGroup.getDisplayText());
tabHost.addTab(spec, OrderGroupTabFragment.class, bundle);
System.out.println("Tab added " + formGroup.getDisplayText());
}
}
return rootView;
}
#Override
public void onStart() {
super.onStart();
tabHost.setCurrentTab(0);
}
public TrafficSafetyOrder getOrder() {
return _order;
}
public void setOrder(TrafficSafetyOrder _order) {
this._order = _order;
}
#Override
public void onDestroyView() {
super.onDestroyView();
try {
_trafficSafetyOrderService.updateTrafficServiceOrder(_order);
} catch (Exception e) {
_logger.log(Level.WARNING, e.getMessage(), e);
}
}
#Override
public void onDetach() {
super.onDetach();
_detached = true;
}
#Override
public void onASyncMethodCompleted(Object receiver, Method method) {
if(_detached)// if fragment is already detached from Activity, do not execute callback
return;
Toast.makeText(getActivity(), receiver != null ? receiver.getClass().getSimpleName() : "NULL" + "." + method != null ? method.getName() : "NULL" + " executed succesfully", Toast.LENGTH_LONG).show();
}
}
OrderGroupTabFragment:
public class OrderGroupTabFragment extends android.support.v4.app.Fragment{
public static final String ORDER_GROUP_LIST_ARG = "ORDER_GROUP_ITEMS";
private List<GroupItem> groupItems;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("Creating Order List View");
View view = inflater.inflate(R.layout.fragment_order_group_tab_list, null);
groupItems = (List<GroupItem>)getArguments().getSerializable(ORDER_GROUP_LIST_ARG);
listView = (ListView)view.findViewById(R.id.order_detail_tab_list_view);
listView.setAdapter(new GroupItemAdapter(getActivity(), groupItems));
System.out.println("Order List View Created");
return view;
}
}
GroupItemAdapter:
public class GroupItemAdapter extends ArrayAdapter<GroupItem> {
private Context _context;
public GroupItemAdapter(Context context, List<GroupItem> groupItems) {
super(context, R.layout.lvi_group_item , groupItems);
this._context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater li = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.lvi_group_item,
parent, false);
holder = new ViewHolder();
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
GroupItem item = getItem(position);
holder.header = (TextView)convertView.findViewById(R.id.tab_header);
holder.isVerified = (CheckBox)convertView.findViewById(R.id.tab_verification_checkbox);
if(item != null)
holder.header.setText(item.getName());
return convertView;
}
private class ViewHolder {
TextView header;
CheckBox isVerified;
}
}
fragment_order_detail.xml:
<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">
<LinearLayout android:id="#+id/order_detail_button_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
style="#android:style/Widget.ActionBar">
<Button android:id="#+id/order_detail_button_undo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_undo"
android:text="Undo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_redo"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_redo"
android:text="Redo"
android:layout_weight="1"/>
<Button android:id="#+id/order_detail_button_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
style="#android:style/Widget.ActionButton"
android:drawableTop="#drawable/ic_action_tick"
android:text="Submit"
android:layout_weight="1"/>
</LinearLayout>
<TextView
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:layout_below="#id/order_detail_button_bar"
android:layout_alignParentStart="true"
android:id="#+id/order_detail_header"/>
<android.support.v4.app.FragmentTabHost android:id="#+id/order_detail_tab_host"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/order_detail_header">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#android:id/tabs"/>
</RelativeLayout>
</android.support.v4.app.FragmentTabHost>
fragment_order_group_tab_list.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/order_detail_tab_list_view"/>
</RelativeLayout>
lvi_group_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="#+id/tab_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"/>
<CheckBox android:id="#+id/tab_verification_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/tab_header"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_toEndOf="#id/tab_header"
android:text="#string/lvi_group_item_verification_succesfull"
/>
</RelativeLayout>
gr33tz gangfish
Got it working.
I took the wrong fragmentmanager to pass to the tabhost.setup() method in my OnCreateView method in the DetailFragment.
tabHost.setup(getActivity(), getChildFragmentManager() , android.R.id.tabcontent);

Categories

Resources