I'm trying to get my replaced fragment to appear in the detail fragment but after debugging my app on a tablet emulator and selecting the necessary list view item, the log cat gives me this error:
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 (com.apptacularapps.exitsexpertlondonlite:id/detail_container) for fragment FragmentWCBank{3b4ea8fb #0 id=0x7f0c0050}
I really don't understand why I'm getting this error when my fragment is there within my project. Does anyone know what I'm doing wrong and how to fix this?
FragmentWCLine.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class FragmentWCLine extends android.support.v4.app.Fragment {
public final static String EXTRA_MESSAGE = "Station_key";
private class WC {
private CharSequence station;
private CharSequence zone;
private Class<? extends Activity> activityClass;
private Class<? extends android.support.v4.app.Fragment> fragmentClass;
public WC(int stationResId, int zoneResId, Class<? extends Activity> activityClass, Class<? extends android.support.v4.app.Fragment> fragmentClass) {
this.fragmentClass = fragmentClass;
this.activityClass = activityClass;
this.station = getResources().getString(stationResId);
this.zone = getResources().getString(zoneResId);
}
#Override
public String toString() { return station.toString(); }
public String getzone(){ return zone.toString(); }
}
private static WC[] mWC;
private boolean mTwoPane;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_wc_line, container, false);
// Instantiate the list of stations.
mWC = new WC[]{
new WC(R.string.bank, R.string.zone_1, WCBankActivity.class, FragmentWCBank.class),
new WC(R.string.wat, R.string.zone_1, WCWATActivity.class, FragmentWCWAT.class)
};
final ListView listView = (ListView)v.findViewById(R.id.list_wc);
listView.setAdapter(new MyAdapter(getActivity(), mWC));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mTwoPane){
setItemNormal();
View rowView = view;
setItemSelected(rowView);
}
else{
Intent intent = new Intent(getActivity(), mWC[position].activityClass);
String station = mWC[position].station.toString();
intent.putExtra(EXTRA_MESSAGE, station);
startActivity(intent);
}
}
public void setItemSelected(View view){
View rowView = view;
view.setBackgroundColor(Color.parseColor("#66CCCC"));
TextView tv0 = (TextView)rowView.findViewById(R.id.list_item_station);
tv0.setTextColor(Color.parseColor("#000099"));
TextView tv1 = (TextView)rowView.findViewById(R.id.list_item_zone);
tv1.setTextColor(Color.parseColor("#000099"));
}
public void setItemNormal()
{
for (int i=0; i< listView.getChildCount(); i++) {
View v = listView.getChildAt(i);
v.setBackgroundColor(Color.TRANSPARENT);
TextView tv0 = ((TextView) v.findViewById(R.id.list_item_station));
tv0.setTextColor(Color.WHITE);
TextView tv1 = ((TextView) v.findViewById(R.id.list_item_zone));
tv1.setTextColor(Color.parseColor("#B5B5B5"));
}
}
});
return v;
}
static class MyAdapter extends BaseAdapter {
static class ViewHolder {
TextView station;
TextView zone;
}
LayoutInflater inflater;
WC[] mWC;
public MyAdapter(Context contexts, WC[] samples) {
this.mWC = samples;
inflater = LayoutInflater.from(contexts);
}
#Override
public int getCount() {
return mWC.length;
}
#Override
public Object getItem(int position) {
return mWC[position];
}
#Override
public long getItemId(int position) {
return 0;
}
/**set selected position**/
private int selectPosition = -1;
public void setSelectPosition(int position){
if(position!=selectPosition){
selectPosition = position;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_dualline, null);
viewHolder = new ViewHolder();
viewHolder.station = (TextView) convertView.findViewById(R.id.list_item_station);
viewHolder.zone = (TextView) convertView.findViewById(R.id.list_item_zone);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.station.setText(mWC[position].station);
viewHolder.zone.setText(mWC[position].getzone());
//change item color
if(position==selectPosition){
convertView.setBackgroundColor(Color.parseColor("#000099"));
viewHolder.station.setTextColor(Color.parseColor("#000099"));
}else {
}
return convertView;
}
}
}
WCBankActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
public class WCBankActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "Station_key";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_wc_bank);
if (savedInstanceState == null) {
// Get the message from the intent
Intent intent = getIntent();
// Notice to specify the sender Activity for the message
String station = intent.getStringExtra(WCBankActivity.EXTRA_MESSAGE);
FragmentWCBank newFragment = new FragmentWCBank();
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
}
}
FragmentWCBank.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentWCBank extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wc_bank, container, false);
return v;
}
}
fragment inflation
fragment_wc_bank.xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/detail_container">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Bank"
android:id="#+id/textView0"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
fragment_wc_line.xml layout
<?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:id="#+id/fragmentwcline">
<ListView
android:id="#+id/list_wc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="false"
android:layout_centerHorizontal="true"/>
</LinearLayout>
activity_main.xml layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/master_container"
android:name="com.apptacularapps.exitsexpertlondonlite.FragmentMainList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
activity_main.xml layout (sw600dp)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/master_container"/>
<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:id="#+id/detail_container"/>
</LinearLayout>
Undesired result
Your code transaction.replace(R.id.detail_container...Now this may be the correct UI element. I am assuming this is the correct UI. If so, fragment_wc_bank layout xml does not have that ID detail_container, hence you get error, simple as that. However activity_main.xml has that ID, again I am assuming detail_container is the correct UI that you want.
Suggested code FROM:
setContentView(R.layout.fragment_wc_bank);
TO:
setContentView(R.layout.activity_main.xml);
Notes:
activity_main.xml is the only difference between the 2 codes above.
This is a common error but we all have to learn from this. Learn more about layouts. It is a critical knowledge in making Android apps.
There are 2 different activity_main.xml files you posted. They should at least be similar. Otherwise you could be very confused.
Your activity is trying to inflate a layout, then place a fragment into it in place of the view detail_container. detail_container does not exist in that layout- either you forgot to add it or you're inflating the wrong thing. I notice you're inflating R.layout.fragment_wc_bank for both the fragment and the main activity, my guess is you're inflating the wrong layout in the activity.
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);
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;
}
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);
I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout file**
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.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="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.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="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->
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