Android YoutubePlayerView video is not visible - java

I'm using PierfrancescoSoffritti YouTubePlayerView but the videos are not visible in recycler view only the sound and thumbnail is showing. Need some help.
Here is the youtubeplayer xml
<?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:orientation="vertical" android:layout_height="match_parent">
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="#+id/video_player" app:autoPlay="false" app:videoId="S0Q4gqBUs7c" app:showFullScreenButton="true"
app:useWebUi="true" app:enableLiveVideoUi="true" app:enableAutomaticInitialization="true" />
</LinearLayout>
The Adapter Class where the youtubeplayerview is initialized
package aritra.code.chatters.Adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import aritra.code.chatters.MainActivity;
import aritra.code.chatters.Models.DummyPOJO;
import aritra.code.chatters.R;
import aritra.code.chatters.databinding.SampleVideoBinding;
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
Context context;
List<DummyPOJO> list;
public VideoAdapter(Context context, List<DummyPOJO> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public VideoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_video, parent, false);
return new VideoViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VideoViewHolder holder, int position) {
DummyPOJO data = list.get(position);
((MainActivity) context).addLifeCycleCallBack(holder.binding.videoPlayer);
holder.binding.videoPlayer.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
#Override
public void onReady(#NotNull YouTubePlayer youTubePlayer) {
super.onReady(youTubePlayer);
String videoId = data.getVideoId();
youTubePlayer.cueVideo(videoId, 0);
youTubePlayer.play();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
SampleVideoBinding binding;
public VideoViewHolder(#NonNull View itemView) {
super(itemView);
binding = SampleVideoBinding.bind(itemView);
}
}
}
Everything works fine except the visibility of the video

The issue seems to stem from adding the following inside manifest.
android:hardwareAccelerated="false"
Once that is removed, everything works fine.

Related

How to fix EditText part from ListView inside fragment?

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);

getting java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm getting error in crimeholder class , which states
'java.lang.NullPointerException:Attempt to invoke virtual method
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference'
I copied pasted most of the code from the book which I bought from amazon.
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
//
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.support.v4.app.Fragment;
public class CrimeActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.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.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
public CheckBox mSolvedCheckBox;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.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)
{
mCrime.setmTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getmDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setmSolved(isChecked);
}
});
return v;
}
}
//
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
if (sCrimeLab == null) {
sCrimeLab = new CrimeLab(context);
}
return sCrimeLab;
}
private CrimeLab(Context context) {
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setmTitle("Crime #" + i);
crime.setmSolved(i % 2 == 0); // Every other one
mCrimes.add(crime);
}
}
public List<Crime> getCrimes() {
return mCrimes;
}
public Crime getCrime(UUID id) {
for (Crime crime : mCrimes) {
if (crime.getmId().equals(id)) {
return crime;
}
}
return null;
}
}
//
import android.support.v4.app.Fragment;
public class CrimeListActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new CrimeListFragment();
}
}
//
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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.TextView;
import java.util.List;
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
}
private class CrimeHolder extends RecyclerView.ViewHolder {
private Crime mCrime;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_crime, parent, false));
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
}
public void bind(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getmTitle());
mDateTextView.setText(mCrime.getmDate().toString());
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new CrimeHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
holder.bind(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
}
}
//
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
}
}
}
//activity_fragment.xmml
FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_container"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CrimeActivity">
</FrameLayout>
//fragment_crime.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"/>
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/crime_title_hint" />
<TextView
style="?android:listSeparatorTextViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"/>
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_solved_label"/>
</LinearLayout>
//
//fragment_crime_list.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
//list_item_crime.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="crime_title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/crime_date"
android:text="crime_date"/>
Try as follows
In your CrimeAdapter under onCreateViewHolder, Pass views to CrimeHolder
class
#NonNull
#Override
public CrimeHolder onCreateViewHolder(#NonNull ViewGroup viewGroup,int i){
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate( R.layout.list_item_crime, viewGroup, false );
// here pass view as a constructor
return new CrimeHolder(view);
}
In your CrimeHolder, set to superclass and retrieve other property as follows
private class CrimeHolder extends RecyclerView.ViewHolder{
private TextView mTitleTextView;
private TextView mDateTextView;
CrimeHolder(View view){
super(view);
mTitleTextView = view.findViewById(R.id.textView);
mDateTextView = view.findViewById(R.id.textView2);
}
}
You are not finding the views properly, you are calling super() and in the same time trying to find the textviews from itemView which I don't where are you initialing it. Do the following:
Replace
mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
with
mTitleTextView = (TextView) findViewById(R.id.crime_title);
mDateTextView = (TextView) findViewById(R.id.crime_date);
OR
Replace
super(inflater.inflate(R.layout.list_item_crime, parent, false));
with
itemView = (ViewGroup) inflater.inflate(R.layout.list_item_crime, parent, false);

How to create grids using Total rows and columns in android dynamically

I am new to android. I want to build a grid based on total rows and columns and display in view.After creating a grid I need to place icon in one of the grid. The icon will come from the server URL. The grid should be like this below.
That created grid should fit in the screen. How do I do that? Can someone give me a code sample. Thanks in advance!!!
res/layout/ gridview_android_example_with_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/gridview_android_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:columnWidth="100dp"
android:gravity="center"
android:minHeight="90dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
AndroidGridViewDisplayImages.java
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class AndroidGridViewDisplayImages extends AppCompatActivity {
GridView androidGridView;
// Dummy Array of images (Replace with your own values)
Integer[] imageIDs = {
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
R.drawable.email, R.drawable.mobile, R.drawable.alram,
R.drawable.android, R.drawable.wordpress, R.drawable.web,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview_android_example_with_image);
androidGridView = (GridView) findViewById(R.id.gridview_android_example);
androidGridView.setAdapter(new ImageAdapterGridView(this));
androidGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(), "Grid Item " + (position + 1) + " Selected", Toast.LENGTH_LONG).show();
}
});
}
public class ImageAdapterGridView extends BaseAdapter {
private Context mContext;
public ImageAdapterGridView(Context c) {
mContext = c;
}
public int getCount() {
return imageIDs.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView mImageView;
if (convertView == null) {
mImageView = new ImageView(mContext);
mImageView.setLayoutParams(new GridView.LayoutParams(130, 130));
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setPadding(16, 16, 16, 16);
} else {
mImageView = (ImageView) convertView;
}
mImageView.setImageResource(imageIDs[position]);
return mImageView;
}
}
}

How can i make TextView selected in GridView based on clicked position?

I am using a fragment where i am using a GridView to generate some categories. When user selects a category i am replacing the previous fragment with a new fragment which is used to take the details of the category. But when i get back to the previous fragment where the categories are displayed i want to make the category selected on which the user previously clicked. I have tried to use selector but it is not working for me. Here goes my code.
Here is my layout xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="20dp"
>
<GridView
android:id="#+id/hindernisTypGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="190dp"
android:verticalSpacing="20dp"
android:layout_below="#+id/topBar"
android:horizontalSpacing="5dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
/>
</LinearLayout>
Here is my custom xml for gridview
<?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:orientation="vertical"
android:layout_width="190dp"
android:layout_height="180dp"
android:padding="2dp"
tools:ignore="MissingPrefix"
>
<TextView
android:textColor="#color/redText"
android:textSize="37.14sp"
android:layout_gravity="center_horizontal"
android:gravity="center_vertical"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="180dp"
android:text="OBW"
android:id="#+id/hindernisTypTextView"
fontPath="DBSansRegular.otf"
android:textAppearance="#style/DBSansRegular"
android:background="#drawable/grid_view_item_selector"
/>
</RelativeLayout>
Here is my selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/redText" android:state_pressed="true"/>
</selector>
Here is the Fragment which is used to display the categories
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps());
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
}
The adapter i have used for displaying the categories in gridview
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps){
this.context = context;
this.hindernisTyps = hindernisTyps;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
return convertView;
}
}
When user going to details fragment send that selected category to main activity or shared preference or constant but not try to rely on onSaveInstanceState()
Now when you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment Lifecycle.
Now start form onCreateView()
So add a boolean isRestoredFromBackstack to fragment and follow code below:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mIsRestoredFromBackstack = false;
}
#Override
public void onResume()
{
super.onResume();
if(mIsRestoredFromBackstack)
{
// The fragment restored from backstack,
// get selected state and set category selected again!
}
}
#Override
public void onDestroyView()
{
super.onDestroyView();
mIsRestoredFromBackstack = true;
}
OR
there is another simple solution.... depends on situation
just use add() not replace()
Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();
Here is the way by which i have solved my problem. Before starting the new fragment i am storing the position in a variable named previousPosition which was initialized whit a negative value of -1. Then i am passing the previousPosition in the Adapter. The code is given below.
The updated Fragment class
package com.example.anikdey.railwayapp.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.adapters.HindernisTypGridViewAdapter;
import com.example.anikdey.railwayapp.models.HindernisTyp;
public class HindernisTypFragment extends Fragment {
private GridView projectListGridView;
private View view;
private HindernisTyp hindernisTyp;
private HindernisTypGridViewAdapter hindernisTypGridViewAdapter;
private OnHindernisTypSelectedListener hindernisTypSelectedListener;
private int previousPosition = -1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.kategorie_wahlen_grid_view, container, false);
projectListGridView = (GridView) view.findViewById(R.id.kategoryWahlenGridView);
hindernisTyp = new HindernisTyp();
hindernisTypGridViewAdapter = new HindernisTypGridViewAdapter(getActivity().getApplicationContext(), hindernisTyp.getHindernisTyps(), previousPosition);
projectListGridView.setAdapter(hindernisTypGridViewAdapter);
projectListGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
hindernisTypSelectedListener.setHindernisTyp(hindernisTyp.getHindernisTyps().get(position).getHindernisTypName());
hindernisTypSelectedListener.enableCancelButton(true);
previousPosition = position;
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, new DetailsFragment(),"DetailsFragment");
fragmentTransaction.addToBackStack("df");
fragmentTransaction.commit();
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
hindernisTypSelectedListener = (OnHindernisTypSelectedListener) activity;
} catch (ClassCastException e) {
}
}
public interface OnHindernisTypSelectedListener {
public void setHindernisTyp(String hindernisTyp);
public void enableCancelButton(boolean state);
}
}
Here is the updated Adapter class
package com.example.anikdey.railwayapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.anikdey.railwayapp.R;
import com.example.anikdey.railwayapp.models.HindernisTyp;
import java.util.ArrayList;
import java.util.List;
public class HindernisTypGridViewAdapter extends BaseAdapter {
private Context context;
private int previousPosition;
private List<HindernisTyp> hindernisTyps = new ArrayList<HindernisTyp>();
public HindernisTypGridViewAdapter(Context context, List<HindernisTyp> hindernisTyps, int previousPosition){
this.context = context;
this.hindernisTyps = hindernisTyps;
this.previousPosition = previousPosition;
}
#Override
public int getCount() {
return hindernisTyps.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private static final class ViewHolder {
private TextView hindernisTypTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.hindernis_typ_grid_view_custom_layout, null, true);
holder = new ViewHolder();
holder.hindernisTypTextView = (TextView) convertView.findViewById(R.id.hindernisTypTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(position == previousPosition) {
holder.hindernisTypTextView.setBackgroundColor(context.getResources().getColor(R.color.redText));
holder.hindernisTypTextView.setTextColor(context.getResources().getColor(R.color.whiteText));
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
} else {
holder.hindernisTypTextView.setText(hindernisTyps.get(position).getHindernisTypName());
}
return convertView;
}
}

Adding swipe functionality and a textview to a Image Slideshow Android app - Comic

I need to add swipe functionality and a textview to a Image Slideshow Android App implementation - which is actually a comic about the life of St. Don Bosco with images that go along with the story. Gallery widget did the job but sadly now deprecated :(
I managed to do the following and navigation between images is only possible by clicking the thumbnails at the bottom:
Screenshots - Genymotion
Current Java:
package org.dbysmumbai.donbosco;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dbyouth_activity);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.empty_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.dbyouth000, R.drawable.dbyouth001,
R.drawable.dbyouth001b, R.drawable.dbyouth002};
private Integer[] mImageIds = {
R.drawable.dbyouth000, R.drawable.dbyouth001, R.drawable.dbyouth001b,
R.drawable.dbyouth002};
}
XML:
<?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">
<ImageSwitcher android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Gallery android:id="#+id/gallery"
android:background="#55000000"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center_vertical"
android:spacing="16dp"
/>
</RelativeLayout>
Thanks for reading. Any help/links will be greatly and irrevocably appreciated :)
EDIT:
I'm using this code example for a viewpager.. how can I add a textview at the bottom that will detail the story
please please explain by editing this code .. Thanks a lot :)
MainActivity.java
package com.manishkpr.viewpagerimagegallery;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
}
}
ImageAdapter.java
package com.manishkpr.viewpagerimagegallery;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
activity_main.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"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
There were no thumbnails available with this code example and no left/right arrow to indicate swiping. I don't know to implement those. Maybe some help please?
Hi There !!
Did you try android ViewPager component?
if not please go through this .Its a very useful component.It
solved all your problems.
1:
http://developer.android.com/training/animation/screen-slide.html
If gallery is giving problem then go for HorizontalScrollView component of android.
This project is divided in to three tasks. First one is building Grid View display of all the images. Second is showing selected grid image in full screen slider. And finally adding pinch zooming functionality to fullscreen image.
Check out this tutorial, may be helpful for you to achieve your target

Categories

Resources