My application has 2 tabs with two different layouts. when i run the application, the fragment which is supposed to be shown in tab1(position 0) displays in tab2, and the fragment which is supposed to be in tab2(position 1) is not displaying. Also when i swipe the screen the tab focus is not changing in the tablayout
I have given my code below
MainActivity.java
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener
{
TabLayout tabLayoutTL;
TabLayout.Tab linearTab, gridTab;
ViewPager viewPagerVP;
ViewPagerAdapter viewPagerAdapter;
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPagerVP.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPagerVP = (ViewPager)findViewById(R.id.viewPagerVP);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerVP.setAdapter(viewPagerAdapter);
tabLayoutTL = (TabLayout)findViewById(R.id.tabLayoutTL);
linearTab = tabLayoutTL.newTab();
gridTab = tabLayoutTL.newTab();
linearTab.setText("Linear");
gridTab.setText("Grid");
tabLayoutTL.addTab(linearTab, 0);
tabLayoutTL.addTab(gridTab, 1);
tabLayoutTL.setOnTabSelectedListener(this);
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String FRAG_TYPE = "frag_type";
int fragType;
RecyclerView recyclerViewRv;
public MainFragment() {}
public static MainFragment newInstance(int fragType) {
MainFragment mainFragment = new MainFragment();
Bundle args = new Bundle();
args.putInt(FRAG_TYPE, fragType);
mainFragment.setArguments(args);
return mainFragment;
}
private void initialize() {
recyclerViewRv = (RecyclerView)getActivity().findViewById(R.id.recyclerViewRv);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
new BackBone().execute();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
fragType = getArguments().getInt(FRAG_TYPE);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_linear, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
class BackBone extends AsyncTask<Void, Void, ArrayList<DataRecord>> {
ProgressDialog progressDialog;
private static final String flickrUrl = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&nojsoncallback=1";
private String getData() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(flickrUrl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String data = EntityUtils.toString(httpEntity);
return data;
} catch (Exception e) {
return "exception";
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait .......");
progressDialog.show();
}
@Override
protected ArrayList<DataRecord> doInBackground(Void... params) {
ArrayList<DataRecord> dataRecords = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(getData());
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
DataRecord dataRecord = new DataRecord();
dataRecord.setName(jsonObject1.getString("title"));
JSONObject mediaJSONObject = jsonObject1.getJSONObject("media");
dataRecord.setUrl(mediaJSONObject.getString("m"));
dataRecords.add(dataRecord);
}
} catch (Exception e) {}
return dataRecords;
}
@Override
protected void onPostExecute(ArrayList<DataRecord> dataRecords) {
super.onPostExecute(dataRecords);
DataRecordAdapter dataRecordAdapter = new DataRecordAdapter(getActivity(), dataRecords, fragType);
if (fragType == 1) {
recyclerViewRv.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewRv.setBackgroundColor(Color.GREEN);
} else if (fragType == 2){
recyclerViewRv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerViewRv.setBackgroundColor(Color.BLUE);
}
recyclerViewRv.setAdapter(dataRecordAdapter);
progressDialog.dismiss();
}
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0 :
MainFragment mainFragment = MainFragment.newInstance(1);
return mainFragment;
case 1 :
MainFragment mainFragment1 = MainFragment.newInstance(2);
return mainFragment1;
default :
return null;
}
}
@Override
public int getCount() {
return 2;
}
}
I am sure there is no problem with the fragmets. I think the problem is with the tablayout. I cant figure out where exactly the problem is.
DataRecordAdapter.java
public class DataRecordAdapter extends RecyclerView.Adapter<DataRecordAdapter.MyViewHolder> {
ArrayList<DataRecord> dataRecords;
Context context;
int flag;
LayoutInflater layoutInflater;
public DataRecordAdapter(Context context, ArrayList<DataRecord> dataRecords, int flag) {
this.context = context;
this.dataRecords = dataRecords;
this.flag = flag;
layoutInflater = (LayoutInflater.from(context));
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if (flag == 1) {
view = layoutInflater.inflate(R.layout.linear_data_layout, parent, false);
} else {
view = layoutInflater.inflate(R.layout.grid_data_layout, parent, false);
}
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DataRecord dataRecord = dataRecords.get(position);
holder.textViewTV.setText(dataRecord.getName());
Picasso.with(context).load(dataRecord.getUrl()).into(holder.imageViewIV);
}
@Override
public int getItemCount() {
return dataRecords.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewTV;
ImageView imageViewIV;
public MyViewHolder(View itemView) {
super(itemView);
textViewTV = (TextView)itemView.findViewById(R.id.textViewTV);
imageViewIV = (ImageView)itemView.findViewById(R.id.imageViewIV);
}
}
}
DataRecord.java
public class DataRecord {
String name, url;
public String getName() {
return name;
}
[![enter image description here][1]][1]
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
take a look at the images guys. tab 1 is empty and tab 2 shows the content which shoud be on tab 1. tab 2 content is not displayed.
You should call:
viewPagerVP.setCurrentItem(0);
on onCreate
function of MainActivity.
I know the thread is not live but this might help someone and save a day which I had to spend. I ran into the same problem. The problem was same viewIDs on both fragments. Definitely, viewpager and fragment should have handled this but as somehow they didn't.
For me this was happening for two different fragments namely FragmentHome and FragmentNotification. Both had to show data using recyclerView. Home was first fragment in left and next was notification. But first was shown blank and home content was shown on next tab where notification content was expected. As both had same recyclerViews, I wrote a layout_recycler_wrapper.xml to reuse the code. In which a RelativeLayout (R.id.rl_wrapper) was there with a recyclerView.
Root cause was I was including a this layout_recycler_wrapper in both fragments layout files using <include>
. So same ID (R.id.rl_wrapper) of that wrapper viewGroup (RelativeLayout) were used more than once.
Then I wrote wrapper code directly in fragment's xml files instead of using <include>
tag. Then changed id of RelativeLayout wrappers as R.id.rl_wrapper_home and R.id.rl_wrapper_notification in respective files.
On the next run, first fragment was magically FragmentHome. Yahooo.....:)
So ultimately, use of views with same ID (even if in different fragments) was creating problem. This is one possible reason. Check your XML file and remove possible reuses of IDs, that might solve problem for you too.
来源:https://stackoverflow.com/questions/38341226/tablayoutview-pager-is-not-displaying-the-fragment-in-position-0