I'm moving my first steps into android, so sorry if this is a stupid question.
I've followed this tutorial to implement a DialogFragment containing a ListView.
This is the ColorDialogFragment.java:
public class ColorDialogFragment extends DialogFragment {
String[] listItems = { "Red", "Blue", "Green"};
ListView myList;
String ipAddress;
public static ColorDialogFragment newInstance(String ipAddress) {
Bundle args = new Bundle();
args.putString("ipAddress",ipAddress);
ColorDialogFragment fragment = new ColorDialogFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ipAddress = getArguments().getString("ipAddress");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_fragment, null, false);
myList = (ListView) view.findViewById(R.id.list);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listItems);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String colorHex;
switch (i){
case 1:
colorHex = "#FF0000";
break;
case 2:
colorHex = "#0000FF";
break;
case 3:
colorHex = "#00FF00";
break;
default:
dismiss();
return;
}
ClientAsyncTask clientAsyncTask = new ClientAsyncTask(ipAddress, colorHex);
clientAsyncTask.execute();
dismiss();
}
});
}
private class ClientAsyncTask extends AsyncTask<Void, Void, Void> {
...
}
}
And this is dialog_fragment.xml:
<?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">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
The problem is that when I click a list item onItemClick() is not called (and obviously I don't understand why).
I found out by myself that the problem were the wrong indexes in switch statement (starting from 0 and not from 1, obviously).
Related
I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?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:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"
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'm trying to launch my fragment in the detail fragment & highlight the selected list item (code is there in FragmentWCLine.java) in two pane mode but for some reason it won't do so. Seems to work fine in single pane mode but when it comes to two pane mode it seems to ignore my code in the if(mTwoPane) section within FragmentWCLine.java and then decides to launch an activity rather than showing the fragment in the detail fragment & highlighting the selected list item. In FragmentWCLine.java, I'm not sure what to do with startActivity(new Intent(getActivity(), mWC[position].fragmentClass));. Also FragmentLineChooserList newFragment = new FragmentLineChooserList(); needs to be changed to something else but I have no idea as to what that would be. How can I prevent the mTwoPane code from being ignored so that it does what it is supposed to along with the above that I want to achieve?
WCLineActivity.java
public class WCLineActivity extends ActionBarActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#66CCCC")));
actionBar.setTitle(Html.fromHtml("<font color='#000099'>Hello World</font>"));
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
FragmentWCLine newFragment = new FragmentWCLine();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
}
}
FragmentWCLine.java
public class FragmentWCLine extends android.support.v4.app.Fragment {
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;
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
public boolean mTwoPane;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_wc_line, container, false);
if (getActivity().findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}else{
mTwoPane = false;
}
// Instantiate the list of stations.
mWC = new WC[]{
new WC(R.string.bank, R.string.zone_1, WCAActivity.class, FragmentWCA.class),
new WC(R.string.wat, R.string.zone_1, WCBActivity.class, FragmentWCB.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);
Fragment newFragment;
switch (position) {
case 0:
newFragment = new FragmentWCA();
break;
case 1:
newFragment = new FragmentWCB();
break;
default:
newFragment = new FragmentWCA();
break;
}
WCLineActivity activity = (WCLineActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
Intent intent;
switch (position) {
case 0:
intent = new Intent(getActivity(), WCAActivity.class);
break;
case 1:
intent = new Intent(getActivity(), WCBActivity.class);
break;
default:
intent = new Intent(getActivity(), WCAActivity.class);
break;
}
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;
}
#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());
return convertView;
}
}
}
FragmentWC.java
public class FragmentWC extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wc, container, false);
return v;
}
}
fragment_wc.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>
My guess is you need to init boolean before fragment transaction:
if (findViewById(R.id.detail_container) != null) {
mTwoPane = true;
}
FragmentWCLine newFragment = new FragmentWCLine();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.master_container, newFragment);
transaction.commit();
Update:
Also update click listener:
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);
Fragment newFragment;
switch (position){
case 0:
newFragment = new FragmentWCBank ();
break;
case 1:
newFragment = new FragmentWCWAT();
break;
default:
newFragment = new FragmentWCBank ();
break;
}
WCLineActivity activity = (WCLineActivity) view.getContext();
FragmentTransaction transaction = activity .getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
}
else{
Intent intent;
switch (position){
case 0:
intent = new Intent(getActivity(), WCBankActivity.class);
break;
case 1:
intent = new Intent(getActivity(), WCWATActivity.class);
break;
default:
intent = new Intent(getActivity(), WCBankActivity.class);
break;
}
startActivity(intent);
}
}
When I click in an item of the List the method OnItemClick is not ben called. I'm trying to call another activity to show more information about that "AnaliseEstrutural". What will be in the List is the value Brunton or Clar defined for ehBrunton . Then when the user clicks on a item it will apear the oter information about that "AnaliseEstrutural". But it's not passing by the method.
here is the code:
public class AnalisesPonto extends ListFragment implements OnItemClickListener{
private ArrayList<AnaliseEstrutural> analises;
AnalisesDAO andao;
String idPonto;
private View view;
private ListView analisesList;
private AnalisesAdapter analisesAdapter;
private boolean ehBrunton;
private Intent i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
idPonto = getArguments().getString("id");
andao = new AnalisesDAO(getActivity().getApplicationContext());
analises = andao.relatorioAnalises(idPonto);
ehBrunton = true;
i = new Intent(getActivity().getApplicationContext(), DadosAnalises.class);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.analises_ponto_layout, null);
analisesList = (ListView) view.findViewById(android.R.id.list);
analisesAdapter = new AnalisesAdapter(getActivity().getApplicationContext(), true);
for (int i = 0; i < analises.size(); i++) {
analisesAdapter.add(analises.get(i));
}
analisesList.setAdapter(analisesAdapter);
ViewGroup parent = (ViewGroup) analisesList.getParent();
parent.removeView(analisesList);
analisesList.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Bundle extra = new Bundle();
extra.putBoolean("radio", ehBrunton);
extra.putString("tipo_est", analises.get(position).getTipo());
extra.putString("codigo", analises.get(position).getCodigo());
if(ehBrunton) {
extra.putString("brun_clar", analises.get(position).getBrunton());
} else {
extra.putString("brun_clar", analises.get(position).getClar());
}
extra.putString("azimute", analises.get(position).getAzimute());
extra.putString("direcao", analises.get(position).getDirecao());
extra.putString("quadrante", analises.get(position).getQuadrante());
extra.putString("sentido", analises.get(position).getSentido());
extra.putString("descricao",analises.get(position).getDescricao());
extra.putString("mergulho", analises.get(position).getMergulho());
extra.putString("familia", analises.get(position).getFamilia());
i.putExtra("analise", extra);
startActivity(i);
}
});
return analisesList;
}
}
The layout from the List:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
And here is the Layout of the Element of the List
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/med_angular"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
[RESOLVED] Put the method analisesList.setOnItemClickListener(new OnItemClickListener() inside onActivityCreated instead onCrateView
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
analisesList.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Bundle extra = new Bundle();
extra.putBoolean("radio", ehBrunton);
extra.putString("tipo_est", analises.get(position).getTipo());
extra.putString("codigo", analises.get(position).getCodigo());
if(ehBrunton) {
extra.putString("brun_clar", analises.get(position).getBrunton());
} else {
extra.putString("brun_clar", analises.get(position).getClar());
}
extra.putString("azimute", analises.get(position).getAzimute());
extra.putString("direcao", analises.get(position).getDirecao());
extra.putString("quadrante", analises.get(position).getQuadrante());
extra.putString("sentido", analises.get(position).getSentido());
extra.putString("descricao",analises.get(position).getDescricao());
extra.putString("mergulho", analises.get(position).getMergulho());
extra.putString("familia", analises.get(position).getFamilia());
i.putExtra("analise", extra);
startActivity(i);
}
});
}
What is this removeView for?
parent.removeView(analisesList);
Also shouldn't you be returning the whole view in onCreateView instead of analisesList?
I guess doing the following fill fix the issues
remove "parent.removeView(analisesList);"
return analisesList;
remove implements onOtemClickListener (You are creating an inner annonymous class as mentioned by Raghunandan)