Tablayout + view寻呼机未在位置0显示片段 [英] Tablayout+view pager is not displaying the fragment in position 0

查看:59
本文介绍了Tablayout + view寻呼机未在位置0显示片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有2个选项卡,它们具有两种不同的布局.当我运行该应用程序时,应该显示在tab1(位置0)中的片段显示在tab2中,而应该显示在tab2(位置1)中的片段没有显示.另外,当我滑动屏幕时,标签布局中的标签焦点不会改变

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

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

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

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

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

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

看看这些图像家伙.选项卡1为空,选项卡2显示应在选项卡1上的内容.选项卡2的内容未显示.

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.

推荐答案

我知道该线程不存在,但是这可能会对某人有所帮助,并节省了我必须度过的一天.我遇到了同样的问题.问题是两个片段上都有相同的viewID.当然,viewpager和fragment应该可以解决这个问题,但是由于某种原因,他们没有解决.

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.

对我来说,这发生在两个不同的片段上,分别是 FragmentHome FragmentNotification .两者都必须使用 recyclerView 显示数据.家是左边的第一个片段,下一个是通知.但是首先显示为空白,而下一个选项卡上显示家庭内容,预计通知内容将在此处显示.由于两者具有相同的recyclerViews,因此我编写了 layout_recycler_wrapper.xml 来重复使用代码.其中带有 recyclerView RelativeLayout ( R.id.rl_wrapper ). 根本原因是我在使用<include>的两个片段布局文件中都包含了这个layout_recycler_wrapper.因此,多次使用了该包装器viewGroup( RelativeLayout )的相同ID( R.id.rl_wrapper ).

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.

然后,我直接在片段的xml文件中编写包装器代码,而不是使用<include>标记.然后在各个文件中将 RelativeLayout 包装器的ID更改为 R.id.rl_wrapper_home R.id.rl_wrapper_notification .

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.

在下一次运行中,第一个片段神奇地是 FragmentHome . Yahooo .....:)

On the next run, first fragment was magically FragmentHome. Yahooo.....:)

因此,最终,使用具有相同ID(即使在不同的片段中)的视图也会造成问题.这是一个可能的原因.检查您的XML文件并删除可能重复使用的ID,这也可能为您解决问题.

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.

这篇关于Tablayout + view寻呼机未在位置0显示片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆