I tried a lot of answers to this question but all of them doesn't work for me. I have a view pager and there is three fragments in it but when I run the app on the phone the fragments doesn't appear and the view pager appears empty.
this is the main activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(getSupportFragmentManager(),this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
Toast.makeText(MainActivity.this,
"Selected page position: " + tab.getPosition(), Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
and this is the view pager adapter code :
public class SamplePagerAdapter extends FragmentPagerAdapter {
Context context;
public SamplePagerAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
this.context = context;
}
/**
* #return the number of pages to display
*/
#Override
public int getCount() {
return 3;
}
/**
* #return true if the value returned from {#link #instantiateItem(ViewGroup, int)} is the
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
// BEGIN_INCLUDE (pageradapter_getpagetitle)
/**
* Return the title of the item at {#code position}. This is important as what this method
* <p>
* Here we construct one using the position value, but for real application the title should
* refer to the item's contents.
*/
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "تعلم";
break;
case 1:
title = "الصفحة الرئيسية";
break;
case 2:
title = "التحديات";
break;
}
return title;
}
// END_INCLUDE (pageradapter_getpagetitle)
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Toast.makeText(context, "position 0", Toast.LENGTH_SHORT).show();
return new LearnFragment();
case 1:
Toast.makeText(context, "position 1", Toast.LENGTH_SHORT).show();
return new HomeFragment();
case 2:
Toast.makeText(context, "position 2", Toast.LENGTH_SHORT).show();
return new ChallengesFragment();
}
return null;
}
}
and this is the activity main xml code :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
Remove this code
Related
I am using a view pager in my app the view pager contains three layouts and I can swipe between them well and it shows me the different layout files but when I tried to use java orders on this layout I found that nothing changed in the layout for example I tried to change the text of a textView but I found that it hasn't changed
this is the main activity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(false);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
mViewPager = findViewById(R.id.viewpager);
adapter = new SamplePagerAdapter(this);
tabLayout = findViewById(R.id.tablayout);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(1);
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("تعلم");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.learn, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("الصفحة الرئيسية");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.home, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabThree.setText("التحديات");
tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.challenges, 0, 0);
tabLayout.getTabAt(2).setCustomView(tabThree);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
and this is the java code of the fragment :
// TODO: Rename and change types and number of parameters
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
database = FirebaseDatabase.getInstance();
myRef = database.getReference("posts");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View myView = inflater.inflate(R.layout.fragment_home, container, false);
etAddPost = myView.findViewById(R.id.etAddPost);
TextView tv = myView.findViewById(R.id.testText);
tv.setText("new text");
addPostBtn(myView);
return myView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
and this is the view pager adapter code :
public class SamplePagerAdapter extends PagerAdapter {
Context context;
public SamplePagerAdapter(Context context) {
this.context = context;
}
/**
* #return the number of pages to display
*/
#Override
public int getCount() {
return 3;
}
/**
* #return true if the value returned from {#link #instantiateItem(ViewGroup, int)} is the
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
// BEGIN_INCLUDE (pageradapter_getpagetitle)
/**
* Return the title of the item at {#code position}. This is important as what this method
* <p>
* Here we construct one using the position value, but for real application the title should
* refer to the item's contents.
*/
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "تعلم";
break;
case 1:
title = "الصفحة الرئيسية";
break;
case 2:
title = "التحديات";
break;
}
return title;
}
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at {#code position}. Here we
* inflate a layout from the apps resources and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
// Inflate a new layout from our resources
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert li != null;
View view = null;
switch (position) {
case 0:
view = li.inflate(R.layout.fragment_learn, container, false);
break;
case 1:
view = li.inflate(R.layout.fragment_home, container, false);
break;
case 2:
view = li.inflate(R.layout.fragment_challenges, container, false);
break;
}
// Add the newly created View to the ViewPager
container.addView(view);
// Return the View
return view;
}
/**
* {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
and this is the activity main xml code :
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/color1">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_in_toolbar" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/color1">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
There are two problems which i am trying to solve.I will accept your answer even if you solve one:
1)My tabLayout does not show the title of the current page.It does not show any text.
2)I use instance of the same fragment across the viewPager.Each fragment fetches some data from net and displays in listView.When i move pages slowly across the viewPager all fragments work properly.But when i move fast or use tabs to reach another page some pages never load.Why would it be?
Activity:
public class WorldNews extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_world_news);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager,true);
tabLayout.
}
}
Adapter:
public class FragmentPageAdapter extends FragmentStatePagerAdapter {
private String[] tabTitles = new String[]{"Tab1", "Tab2","Tab3" ,"Tab4" ,"Tab5","Tab6","Tab7","Tab8","Tab9","Tab10","Tab11","Tab12","Tab13","Tab14","Tab15"
,"Tab16","Tab17","Tab18","Tab19"};
public FragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Log.d("Adapter","Case 0 called");
return new LisViewFragment2();
case 1:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=al-jazeera-english&sortBy=top&apiKey=6de");
case 2:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=associated-press&sortBy=top&apiKey=6de");
case 3:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=6de");
case 4:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=cnn&sortBy=top&apiKey=6de");
case 5:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=6de");
case 6:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=independent&sortBy=top&apiKey=6de");
case 7:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=metro&sortBy=top&apiKey=6de");
case 8:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=mirror&sortBy=top&apiKey=6de");
case 9:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=newsweek&sortBy=top&apiKey=6de");
case 10:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=new-york-magazine&sortBy=top&apiKey=6de");
case 11:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reddit-r-all&sortBy=top&apiKey=6de");
case 12:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=reuters&sortBy=top&apiKey=6de");
case 13:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-guardian-uk&sortBy=top&apiKey=6de");
case 14:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-hindu&sortBy=top&apiKey=6de");
case 15:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=67de");
case 16:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-new-york-times&sortBy=top&apiKey=6de");
case 17:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=the-telegraph&sortBy=top&apiKey=6de");
default:
return ListViewFragment.newInstance("https://newsapi.org/v1/articles?source=usa-today&sortBy=top&apiKey=6de");
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public int getCount() {
return 19;
}
}
Here is the layout:
<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="com.example.android.gametalks.Activity.WorldNews">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:layout_below="#id/sliding_tabs"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
Here is the fragment:
public class ListViewFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<GameNews>> {
public static ListViewFragment newInstance(String url) {
Log.d("ListViewFragment","newInstance created");
ListViewFragment f = new ListViewFragment();
// Supply url input as an argument.
Bundle args = new Bundle();
args.putString("url", url);
f.setArguments(args);
return f;
}
List<GameNews> TotalNews;
ListView gameListView;
LinearLayout emptyView;
Button retryButton;
ListAdapter adapter ;
private View progressBar;
final private int game_loader = 0;
ArrayList<String> urls = new ArrayList<>();
String mUrlString;
int index;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUrlString = getArguments().getString("url");
urls.add(mUrlString);
TotalNews = new ArrayList<GameNews>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
ArrayList<GameNews> gameList = new ArrayList<>();
adapter = new ListAdapter(getActivity(),gameList);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
emptyView = (LinearLayout) view.findViewById(R.id.no_internet_view);
progressBar = view.findViewById(R.id.progress_bar);
retryButton = (Button) view.findViewById(R.id.retry_button);
gameListView = getListView();
emptyView.setVisibility(View.INVISIBLE);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(adapter);
//If connected to net start the loader
if(isConnected())
{
getActivity().getSupportLoaderManager().restartLoader(game_loader, null, ListViewFragment.this);
if(progressBar.getVisibility() == View.VISIBLE)
{
Log.d("Fragment","progress bar is still visible");
}
}
//Otherwise show emptyView and hide listView
else
{
emptyView.setVisibility(View.VISIBLE);
gameListView.setVisibility(View.INVISIBLE);
}
}
#Override
public android.support.v4.content.Loader<List<GameNews>> onCreateLoader(int i, Bundle bundle) {
AdManager manager = new AdManager(getActivity());
return new FragmentLoader(getActivity(),urls,1000);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<List<GameNews>> loader, List<GameNews> games) {
progressBar.setVisibility(View.INVISIBLE);
adapter.clear();
TotalNews.addAll(games);
adapter.addAll(games);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<List<GameNews>> loader) {
adapter.clear();
}
//Method checks if there is internet
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getActivity().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
else {
return false;
}
}
}
You are not seeing the title because you have a lot of tabs and there's no place for title. Consider using TabLayout.MODE_SCROLLABLE
tabLayout.setTabMode (TabLayout.MODE_SCROLLABLE);
For First Question
try change tablayout in xml to:
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/red"
android:minHeight="?attr/actionBarSize"
android:elevation="10dp"
app:tabIndicatorColor="#color/black"
app:tabSelectedTextColor="#color/black"
app:tabTextColor="#color/white"
app:tabGravity="fill"
/>
choose your favorits colors
I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>
I have a MainActivity which is a ActionBarActivity with viewPager inside.
Then I have 3 pages.
In the first page there is a tableLayout with tableRow clickListener (inside blocks) from where I would like to start an intent to another layout without hiding TabBar. Here is my code:
MainActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a FirstFragment (defined as a static inner class below).
//return FirstFragment.newInstance(position + 1);
switch(position) {
case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 2: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class FirstFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
//private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.first_fragment, container, false);
createTable(rootView);
return rootView;
}
public static FirstFragment newInstance(String string) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString("msg", "PROVA 1");
fragment.setArguments(args);
return fragment;
}
void createTable(View rootView){
TableLayout ll = (TableLayout) rootView
.findViewById(R.id.tableLayout);
String categorie[];
// MyDatabase db=new MyDatabase(getActivity().getApplicationContext());
// db.open(); //apriamo il db
MyDatabase db = new MyDatabase(getActivity().getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
db.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
Cursor c=db.fetchCategorie(); // query
//startManagingCursor(c);
//qui vediamo invece come reperire i dati e usarli, in questo caso li stampiamo in una textview
int categoriaColumn=c.getColumnIndex(MyDatabase.CategorieMetaData.PRODUCT_CATEGORIA_KEY); //indici delle colonne
//int priceCol=c.getColumnIndex(MyDatabase.ProductsMetaData.PRODUCT_PRICE_KEY);
ArrayList<String> categorieList = new ArrayList<String>();
if(c.moveToFirst()){ //se va alla prima entry, il cursore non è vuoto
do {
categorieList.add(c.getString(categoriaColumn)); //add to arraylist
//productsTv.append("Product Name:"+c.getString(nameCol)+", Price:"+c.getInt(priceCol)+"\n"); //estrazione dei dati dalla entry del cursor
//Log.d("Prova", "PROVA:"+ "Product Name:"+c.getString(categoriaColumn)+", Price:"+c.getInt(priceCol)+"\n");
} while (c.moveToNext());//iteriamo al prossimo elemento
}
db.close();
categorie = categorieList.toArray(new String[categorieList.size()]);
for (int i = 0; i < categorie.length; i++) {
TableRow tbRow = new TableRow(getActivity().getApplicationContext());
tbRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView tv1 = new TextView(getActivity().getApplicationContext());
tv1.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
tbRow.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
ImageView imageView = new ImageView(getActivity().getApplicationContext());
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
tv1.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv1.setId(i);
tv1.setText(categorie[i]);
tv1.setTextColor(Color.parseColor("#000000"));
tbRow.addView(imageView);
tbRow.addView(tv1);
ll.addView(tbRow, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
final String finalCategorie[] = categorie;
final int finalI = i;
final View finalRootView = rootView;
tbRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Intent newIntent = new Intent(MainActivity.this, detailActivity.class);
// newIntent.putExtra("key", strings[finalI]);
Log.d("TEST", "Row selected: " + finalCategorie[finalI]);
// startActivity(newIntent);
// Intent intent = new Intent(getActivity(), EventiFragment.class);
// startActivity(intent);
}
});
}
}
}
public static class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentSecond);
tv.setText(getArguments().getString("msg"));
return v;
}
public static SecondFragment newInstance(String string) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
public static class ThirdFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentThird);
tv.setText(getArguments().getString("msg"));
return v;
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 3");
f.setArguments(b);
return f;
}
}
public static class EventiFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.eventi_fragment, container, false);
TextView tv = (TextView) v.findViewById(R.id.FragmentEventi);
tv.setText(getArguments().getString("msg"));
return v;
}
public static EventiFragment newInstance(String string) {
EventiFragment f = new EventiFragment();
Bundle b = new Bundle();
b.putString("msg", "Prova 2");
f.setArguments(b);
return f;
}
}
}
first_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout1"
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.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:contentDescription="#string/main_photo_description"
android:scaleType="centerCrop"
android:src="#drawable/main_photo" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TableLayout>
</LinearLayout>
</ScrollView>
eventi_fragment.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.alain.ama.caccamo.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/FragmentEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textSize="26sp"/>
So I would create a separate layout, but instead of putting the layout in two separate XML files, put it all in one. For example
<?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"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/intent_replacement"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Here's the stuff for the supposed intent -->
</RelativeLayout>
</RelativeLayout>
So in this you can have one attribute called visible then programmatically you just get the Layout as an object and when an item in the table is clicked on use intentLayoutObject.setVisibility(true)
Likewise when you get back button pressed intentLayoutObject.setVisibility(false)
This is my first experience with android. I'm trying to add items to my ListView.
I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.
I searched around, and I've always found
adapter.notifyDataSetChanged();
but doesn't work for me.
I have created the project with, as I said, Fixed Tabs + Swipe.
I simply want to have listviews which rows have an EditText, a Spinner and a Button.
On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.
my custom Adapter:
package com.andreapivetta.uconverter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;
public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
super(context, resource, bah);
this.context = context;
this.resourceID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resourceID, parent, false);
return rowView;
}
}
fragment_main_dummy.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=".MainActivity$DummySectionFragment" >
<ListView
android:id="#+id/unitListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageButton
android:id="#+id/moreImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_input_add" />
</RelativeLayout>
Row.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">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<EditText
android:id="#+id/unitEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/unitSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/unitEditText" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/unitEditText"
android:layout_alignParentRight="true"
android:onClick="removeItem"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_menu_delete" />
</RelativeLayout>
MainActivity...
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
ArrayList<String> myStringArray1 = new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
String[] myStringArray3 = new String[]{"ddd","eeee"};
String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
public static ArrayAdapter<String> adapter;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
//dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
// ListView
ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
myStringArray1.add("mmm");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
unitListView.setAdapter(adapter);
break;
case 2:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
unitListView.setAdapter(adapter);
break;
case 3:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
unitListView.setAdapter(adapter);
break;
case 4:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
unitListView.setAdapter(adapter);
break;
}
unitListView.setOnItemClickListener(listViewOnClickListener);
// ImageButton
ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
moreImageButton.setOnClickListener(moreListener);
return rootView;
}
public OnClickListener moreListener = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myStringArray1.add("Andrea");
adapter.clear();
adapter.addAll(myStringArray1);
adapter.notifyDataSetChanged();
}
};
public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
};
}
}
Note that I'm working only with the first tab right now...
What am I doing wrong? :)
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter.add("aaaa")
}
}