Android fragment里面创建list在切换后会不会清掉

fragment中创建的list的会随着fragment的切换而销毁掉吗?比如使用的是replace方法切换的fragment

1个回答

不会!但是你退出后就会清空 ,想后面用的话用share保存在本地然后传到你想要传的fragment里面

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Android Fragment切换导致listview有数据也不显示

网上的方法基本上都试过了,没效果。 适配器能进getView(),返回的count也正常、 ``` ```public class Index extends AppCompatActivity { boolean flag = true;//判断数据是否第一加载 private List<listView> listView = new ArrayList<listView>(); private ListFragment listFragment = new ListFragment(); private MineFragment mineFragment = new MineFragment(); private OrderFragment orderFragment = new OrderFragment(); Fragment currentFragment = listFragment; FragmentManager fm = getSupportFragmentManager(); Fragment f = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_index); //解析菜单文件 initData(); final ListViewAdapter listViewAdapter = new ListViewAdapter(Index.this,R.layout.listlayout,listView); final ListView dataList = findViewById(R.id.Data_list); dataList.setAdapter(listViewAdapter); //导航图片设置初始化 ImageView imageView1 = findViewById(R.id.nav_index); ImageView imageView2 = findViewById(R.id.nav_order); ImageView imageView3 = findViewById(R.id.nav_mine); View.OnClickListener listener= new OnClickListener(){ @Override public void onClick(View v) { switch (v.getId()){ case R.id.nav_index: listViewAdapter.notifyDataSetChanged(); dataList.setAdapter(listViewAdapter); showFragment(listFragment); break; case R.id.nav_mine: showFragment(mineFragment); break; default: showFragment(orderFragment); break; } } }; imageView1.setOnClickListener(listener); imageView2.setOnClickListener(listener); imageView3.setOnClickListener(listener); } private void showFragment(Fragment fragment){ FragmentTransaction ft = fm.beginTransaction(); if (currentFragment != fragment){// 判断传入的fragment是不是当前的currentFragmentgit ft.hide(currentFragment);// 不是则隐藏 currentFragment = fragment; // 然后将传入的fragment赋值给currentFragment if (!fragment.isAdded()){ // 判断传入的fragment是否已经被add()过 ft.add(R.id.fragment,fragment).show(fragment).commit(); }else{ ft.show(fragment).commit(); } } } private void initData() { listView list = new listView("系统提示","测试内容信息","2019-3-14",R.drawable.shop1); listView.add(list); listView list1 = new listView("二号餐厅","测试内容信息","2019-3-14",R.drawable.shop2); listView.add(list1); } } 适配器代码 public class ListViewAdapter extends ArrayAdapter { private final int resourceId; public ListViewAdapter(Context context, int resource, List<listView> objects ) { super(context, resource, objects); this.resourceId = resource; } @Override public View getView(int position,View convertView, ViewGroup parent) { listView listView = (listView) getItem(position);// 获取当前项的Fruit实例 View view = LayoutInflater.from(getContext()).inflate(resourceId,null);//实例化一个对象 ImageView listImage = (ImageView) view.findViewById(R.id.shop_img);//获取该布局内的图片视图 TextView listText = (TextView) view.findViewById(R.id.shop_name);//获取该布局内的文字视图 listImage.setImageResource(listView.getImageId());//设置资源 listText.setText(listView.getTitle()); System.out.println("被调用"); return view; } } listview的Xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/index_gray"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:layout_width="match_parent" android:layout_height="500dp" android:background="@color/index_white" android:id="@+id/Data_list"> </ListView> </LinearLayout> </FrameLayout> Activity.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/con_index" android:layout_width="match_parent" android:background="@color/index_gray" android:layout_height="match_parent"> <fragment android:layout_width="match_parent" android:layout_height="600dp" android:name="com.example.administrator.app.ListFragment" android:id="@+id/fragment"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="60dp" android:padding="5dp" android:orientation="horizontal" android:layout_alignParentBottom="true" android:background="@color/index_white"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/nav_index" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/shouye" android:layout_alignParentLeft="true"/> <ImageView android:id="@+id/nav_order" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/dingdan" android:layout_centerHorizontal="true"/> <ImageView android:id="@+id/nav_mine" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/wode" android:layout_alignParentRight="true"/> </RelativeLayout> </LinearLayout> </RelativeLayout>

viewpager+fragment切换fragment的时候会卡顿

viewpager+fragment切换fragment的时候会卡顿,布局不复杂,并且没有太多的数据加载

Fragment切换出现重叠的问题怎么解决?

<FrameLayout android:id="@+id/network_set_content" android:layout_width="match_parent" android:layout_height="match_parent" > <FrameLayout android:id="@+id/network_set_left_list_content" android:layout_width="320dp" android:layout_height="match_parent" android:layout_marginRight="20dp" ></FrameLayout> <FrameLayout android:id="@+id/network_set_right_list_content" android:layout_width="960dp" android:layout_marginLeft="320dp" android:layout_height="match_parent" ></FrameLayout> </FrameLayout> ``` ``` 切换fragment时 FragmentTransaction b = fragmentManager.beginTransaction(); b.replace(R.id.network_set_content, wifiInfoFragment); b.addToBackStack(null); b.commit(); ``` ``` 出现重叠 分别有两个fragment加载在左右两个FrameLayout中了,而且在两个小的FrameLayout中切换fragment是没有问题的,我现在添加一个新的fragment到最外层的FrameLayout就发现之前的两个小的fragment还在 然后我 FragmentManager fragmentManager = getActivity().getFragmentManager(); FragmentTransaction ft_info_list = fragmentManager.beginTransaction(); FragmentTransaction a = fragmentManager.beginTransaction(); FragmentTransaction b = fragmentManager.beginTransaction(); @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ft_info_list.remove(selectorListFragment).commit(); a.remove(wiredNetWorkFragment).commit(); b.replace(R.id.network_set_content, wifiInfoFragment); b.addToBackStack(null); b.commit(); } 这样处理一下也是无效的。。请问有什么办法可以解决呢??

fragment里面如何加载listview

大家好,我是新人。。。。 问一下fragment里面如何加载listview,有详细的步骤最好们,谢谢!

android fragment add如何重新加载页面

我在做一个功能,不能用替换,要用add的,这样返回之后就不会调用上一个页面的 oncreateview方法,或说不能重新加载页面了,求大神解答

求教Fragment和ListView点击跳转

``` package gfxy.com.fragment_dahb; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Web extends Fragment { WebView we; EditText ed1; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.web,null); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().setContentView(R.layout.web); Button bu = (Button) getActivity().findViewById(R.id.webbut); ed1 = (EditText) getActivity().findViewById(R.id.webed); we = (WebView) getActivity().findViewById(R.id.webweb); WebSettings wes = we.getSettings(); wes.setJavaScriptEnabled(true); bu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setweb(); } }); we.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { Toast.makeText(getActivity(), "网页加载完成", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), "加载中", Toast.LENGTH_SHORT).show(); } } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && we.canGoBack()){ we.goBack(); return true; } return false; } public void setweb() { we.loadUrl("http://" + ed1.getText().toString().trim()); we.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } } ``` ``` package gfxy.com.fragment_dahb; import android.app.Fragment; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RadioGroup; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.CategorySeries; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.SimpleSeriesRenderer; /** * Created by Administrator on 2016/4/18. */ public class bt extends Fragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FrameLayout sa = (FrameLayout) getActivity().findViewById(R.id.fm); sa.removeAllViews(); CategorySeries dataset=buildCategoryDataset("测试饼图"); GraphicalView graphicalView=ChartFactory.getPieChartView(getActivity(),dataset, renderer);//饼状图 sa.addView(graphicalView, new RadioGroup.LayoutParams(RadioGroup.LayoutParams.FILL_PARENT, RadioGroup.LayoutParams.FILL_PARENT)); } protected CategorySeries buildCategoryDataset(String title) { CategorySeries categorySeries = new CategorySeries(title); categorySeries.add("胜 ", 30); categorySeries.add("负", 20); categorySeries.add("平", 50); return categorySeries; } int[] colors={Color.BLUE,Color.GREEN,Color.MAGENTA,Color.RED}; DefaultRenderer renderer=buildCategoryRenderer(colors); protected DefaultRenderer buildCategoryRenderer(int[] colors) { DefaultRenderer renderer = new DefaultRenderer(); renderer.setLegendTextSize(20);//设置左下角表注的文字大小 //renderer.setZoomButtonsVisible(true);//设置显示放大缩小按钮 renderer.setZoomEnabled(false);//设置不允许放大缩小. renderer.setChartTitleTextSize(30);//设置图表标题的文字大小 renderer.setChartTitle("统计结果");//设置图表的标题 默认是居中顶部显示 renderer.setLabelsTextSize(20);//饼图上标记文字的字体大小 //renderer.setLabelsColor(Color.WHITE);//饼图上标记文字的颜色 renderer.setPanEnabled(false);//设置是否可以平移 //renderer.setDisplayValues(true);//是否显示值 renderer.setClickEnabled(true);//设置是否可以被点击 renderer.setMargins(new int[]{20, 30, 15, 0}); //margins - an array containing the margin size values, in this order: top, left, bottom, right for (int color : colors) { SimpleSeriesRenderer r = new SimpleSeriesRenderer(); r.setColor(color); renderer.addSeriesRenderer(r); } return renderer; } } ``` ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="30dp" android:orientation="horizontal"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="sadsd" android:textSize="25dp" android:gravity="center" android:background="#0f4"/> </LinearLayout> <android.support.v4.widget.DrawerLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/lv" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="@null" android:choiceMode="singleChoice"> </ListView> <FrameLayout android:id="@+id/fm" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </android.support.v4.widget.DrawerLayout> </LinearLayout> ``` 我想把Web。和bt显示在framelayout里面,求教怎么做? 还有ListView的点击跳转事件之前用还没问题,也不知道干了什么,然后就不能进行跳转了 求解决?? ``` package gfxy.com.fragment_dahb; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends Activity { private String[] name = new String[]{ "饼图","静态折线","动态折线","Web","逐帧动画","缩放,透明,旋转,平移" }; private FragmentManager fm; private FragmentTransaction ft; private FrameLayout fml; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fml = (FrameLayout) findViewById(R.id.fm); ListView lv = (ListView)findViewById(R.id.lv); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); for (int i=0;i<name.length;i++){ Map<String,Object> map = new HashMap<String,Object>(); map.put("name",name[i]); list.add(map); } lv.setAdapter(new SimpleAdapter(this,list,R.layout.content_main,new String[]{"name"},new int[]{R.id.text1})); // int wi = getWindowManager().getDefaultDisplay().getWidth();//获取手机宽度 // int hi = getWindowManager().getDefaultDisplay().getHeight();//获取手机高度 fm = getFragmentManager();//创建一个Fragment ft = fm.beginTransaction();//对Fragment进行添加,删除,替换 ft.replace(R.id.fm,new Fragment1()); ft.commit(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(position==0){ ft = fm.beginTransaction(); ft.replace(R.id.fm,new bt()); ft.commit(); } if(position==1){ ft = fm.beginTransaction(); ft.replace(R.id.fm,new Fragment1()); ft.commit(); } if(position==3){ ft = fm.beginTransaction(); ft.replace(R.id.fm,new Web()); ft.commit(); } } }); } } ```

一个fragment跳转到其它fragment,其它fragment变成了空白页

MainActivity里面有三个fragment的样子,但是呢当我第一个fragment制作了获取新闻功能之后,其它fragment都变成了空白页,请高手指点一下下,谢啦!! 新闻fragment: ![新闻fragment](https://img-ask.csdn.net/upload/201603/04/1457105975_146181.png) 其它fragment: ![其它fragment](https://img-ask.csdn.net/upload/201603/04/1457105997_344946.png) MainActivity: import net.loonggg.fragment.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.Window; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; public class MainActivity extends FragmentActivity { private Fragment[] mFragments; private RadioGroup bottomRg; private FragmentManager fragmentManager; private FragmentTransaction fragmentTransaction; private RadioButton rbOne, rbTwo, rbThree; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); mFragments = new Fragment[3]; fragmentManager = getSupportFragmentManager(); mFragments[0] = fragmentManager.findFragmentById(R.id.fragement_main); mFragments[1] = fragmentManager.findFragmentById(R.id.fragement_bbs); mFragments[2] = fragmentManager.findFragmentById(R.id.fragement_setting); fragmentTransaction = fragmentManager.beginTransaction() .hide(mFragments[0]).hide(mFragments[1]).hide(mFragments[2]); fragmentTransaction.show(mFragments[0]).commit(); setFragmentIndicator(); } private void setFragmentIndicator() { bottomRg = (RadioGroup) findViewById(R.id.bottomRg); rbOne = (RadioButton) findViewById(R.id.rbOne); rbTwo = (RadioButton) findViewById(R.id.rbTwo); rbThree = (RadioButton) findViewById(R.id.rbThree); bottomRg.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { fragmentTransaction = fragmentManager.beginTransaction() .hide(mFragments[0]).hide(mFragments[1]) .hide(mFragments[2]); switch (checkedId) { case R.id.rbOne: fragmentTransaction.show(mFragments[0]).commit(); break; case R.id.rbTwo: fragmentTransaction.show(mFragments[1]).commit(); break; case R.id.rbThree: fragmentTransaction.show(mFragments[2]).commit(); break; default: break; } } }); } } 显示新闻的fragment: import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import com.askdoctor.adapter.NewsAdapter; import com.askdoctor.constans.Constant; import com.askdoctor.entity.News; import com.askdoctor.utils.HttpUtils; import net.loonggg.fragment.R; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class FragmentMain extends Fragment { private NewsAdapter adapter; private List<News> newsList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ListView listNews = (ListView)getView().findViewById(R.id.list_web_view); newsList=new ArrayList<News>(); adapter = new NewsAdapter(getActivity(),newsList); listNews.setAdapter(adapter); HttpUtils.getNewsJSON(Constant.URL_GET_NEWS_LIST, getNewsHandler); } public Handler getNewsHandler=new Handler(){ public void handleMessage(android.os.Message msg){ String jsonData=(String)msg.obj; System.out.println(jsonData); try { JSONArray jsonArray=new JSONArray(jsonData); for (int i = 0; i < jsonArray.length(); i++) { org.json.JSONObject object = jsonArray.getJSONObject(i); String title=object.getString("title"); String desc=object.getString("desc"); String time=object.getString("time"); String content_url=object.getString("content_url"); String pic_url=object.getString("pic_url"); newsList.add(new News(title, desc, time, content_url, pic_url)); } //数据变化后更新adapter adapter.notifyDataSetChanged(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; }; } 变成空白页的fragment: import net.loonggg.fragment.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; public class FragmentBBS extends Fragment { Button btnSendBBS; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_bbs, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); btnSendBBS=(Button)getView().findViewById(R.id.btn_jump_submit); initview(); } private void initview() { btnSendBBS.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent=new Intent(getActivity(),MakeBBS.class); startActivity(intent); } }); } @Override public void onPause() { super.onPause(); } } ``` ``` 这是logcat: 03-03 20:26:52.056: E/memtrack(3342): Couldn't load memtrack module (No such file or directory) 03-03 20:26:52.056: E/android.os.Debug(3342): failed to load memtrack module: -2 03-03 20:26:52.756: E/InputDispatcher(372): channel '4a9f03c8 net.loonggg.fragment/com.askdoctor.ui.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed! 03-03 20:26:54.940: E/Icing(685): Error initializing, resetting corpora: Could not create native index 03-03 20:26:55.240: E/Icing(685): Internal init failed 03-03 20:26:55.240: E/Icing(685): Couldn't handle android.intent.action.PACKAGE_REMOVED intent due to initialization failure. 03-03 20:26:55.240: E/Icing(685): Couldn't handle android.intent.action.PACKAGE_ADDED intent due to initialization failure. 03-03 20:26:55.244: E/Icing(685): Couldn't handle android.intent.action.PACKAGE_REPLACED intent due to initialization failure. 03-03 20:26:57.100: E/memtrack(3367): Couldn't load memtrack module (No such file or directory) 03-03 20:26:57.100: E/android.os.Debug(3367): failed to load memtrack module: -2 03-03 20:26:57.944: E/memtrack(3388): Couldn't load memtrack module (No such file or directory) 03-03 20:26:57.944: E/android.os.Debug(3388): failed to load memtrack module: -2 03-03 20:32:09.552: E/CheckinTask(685): Checkin failed: https://android.clients.google.com/checkin (request #0): org.apache.http.conn.ConnectTimeoutException: Connect to /74.125.23.138:443 timed out 03-03 20:35:50.196: E/BandwidthController(138): Updating quota globalAlert failed (No such file or directory) 再次谢谢各位啦!!!

为什么在fragment里面放的RecyclerView 没写加载会自动加载出来?

直接上代码 把加载fragment写在监听里可是程序一运行就已经显示了 package com.example.bmvod.fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private GalleryAdapter mAdapter; private List<Integer> mDatas; private FirstFragment firstFragment; private SecondFragment secondFragment; // private ThirdFragment thirdFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initDatas(); mRecyclerView = (RecyclerView) findViewById(R.id.recid1); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(linearLayoutManager); mAdapter = new GalleryAdapter(this, mDatas); mAdapter.setOnItemClickLitener(new GalleryAdapter.OnItemClickLitener() { @Override public void onItemClick(View view, int position) { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); switch (position) { case 0: firstFragment = new FirstFragment(); transaction.add(R.id.fragment, firstFragment); hideAllFragments(transaction); transaction.show(firstFragment); break; case 1: secondFragment = new SecondFragment(); transaction.add(R.id.fragment, secondFragment); hideAllFragments(transaction); transaction.show(secondFragment); break; } transaction.commit(); } }); mRecyclerView.setAdapter(mAdapter); } private void hideAllFragments(FragmentTransaction ft) { if (firstFragment != null) { ft.hide(firstFragment); } if (secondFragment != null) { ft.hide(secondFragment); } } private void initDatas() { mDatas = new ArrayList<Integer>(Arrays.asList(R.drawable.bottom1, R.drawable.bottom2, R.drawable.bottom3, R.drawable.bottom4, R.drawable.bottom5, R.drawable.bottom1, R.drawable.bottom2, R.drawable.bottom3, R.drawable.bottom4)); } private void setDefaultFragment() { FragmentManager fm = getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); firstFragment = new FirstFragment(); transaction.replace(R.id.fragment, firstFragment); transaction.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } ``` ``` package com.example.bmvod.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by bmvod on 2016/6/29. */ public class FirstFragment extends Fragment { private RecyclerView mRecyclerView; private GalleryAdapter2 mAdapter; private List<Integer> mDatas; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.firstfragmentlayout, container, false); initDatas2(); mRecyclerView = (RecyclerView) view.findViewById(R.id.fragmengrecv1); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(linearLayoutManager); mAdapter = new GalleryAdapter2(getActivity(), mDatas); mRecyclerView.setAdapter(mAdapter); return view; } private void initDatas2() { mDatas = new ArrayList<Integer>(Arrays.asList(R.drawable.smalltop1, R.drawable.smalltop2, R.drawable.smalltop3, R.drawable.smalltop4, R.drawable.smalltop5, R.drawable.smalltop1, R.drawable.smalltop2, R.drawable.smalltop3, R.drawable.smalltop4)); } } ``` ```

实现FragmentTabhost+ViewPager+Fragment时出现类转换异常

百思不得其解为什么会出现这种类转换错误。也试过不少方法,实在不得其所。 请大触们不吝赐教,谢谢~ 运行报错: > E/AndroidRuntime: FATAL EXCEPTION: main Process: com.wolfgy.news.newsclient, PID: 1109 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wolfgy.news.newsclient/com.wolfgy.news.newsclient.MainActivity}: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.v4.view.ViewPager at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5045) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to android.support.v4.view.ViewPager at com.wolfgy.news.newsclient.MainActivity.initView(MainActivity.java:84) at com.wolfgy.news.newsclient.MainActivity.onCreate(MainActivity.java:52) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)  at android.app.ActivityThread.access$800(ActivityThread.java:135)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:136)  at android.app.ActivityThread.main(ActivityThread.java:5045)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)  at dalvik.system.NativeStart.main(Native Method)  备注:这里说的MainActivity.java:84指的是viewPager = (ViewPager)findViewById(R.id.main_viewPager); 这一行。 MainActivity代码如下 ``` public class MainActivity extends FragmentActivity { FragmentTabHost fragmentTabHost; SlidingMenu slidingMenu; List<Fragment> list = new ArrayList<Fragment>(); String[] titles={"新闻中心" ,"博客频道","体育频道","科技频道","财经频道","视频","影音娱乐","读书频道","女性频道","男性频道","军事频道","汽车新闻","教育频道","房地产","游戏频道","星座频道"}; Class[] fragmentArray = {HeadLineFragment.class, BlogFragment.class, SportsFragment.class, ScientistFragment.class,EconomicsFragment.class, VideoFragment.class, EntertainmentFragment.class, ReadingFragment.class, FemaleFragment.class, MaleFragment.class, MilitaryFragment.class,CarsFragment.class, EducationFragment.class, HouseFragment.class, GamesFragment.class,ConstellationFragment.class}; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initView(); } private void initView(){ fragmentTabHost = (FragmentTabHost)findViewById(R.id.main_fragmentTabHost); fragmentTabHost.setup(this,getSupportFragmentManager(),R.id.main_viewPager); int count = titles.length; for (int i = 0; i < count; i++) { TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(titles[i]).setIndicator(getTabItemView(i)); fragmentTabHost.addTab(tabSpec,fragmentArray[i],null); fragmentTabHost.setTag(i); } fragmentTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { int position = fragmentTabHost.getCurrentTab(); viewPager.setCurrentItem(position); } }); //初始化ViewPager viewPager = (ViewPager)findViewById(R.id.main_viewPager); initPage(); viewPager.setAdapter(new MainActivityFragmentPagerAdapter(getSupportFragmentManager())); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){ @Override public void onPageSelected(int position) { fragmentTabHost.setCurrentTab(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } }); } /** * 初始化Fragment */ private void initPage(){ HeadLineFragment headLine = new HeadLineFragment(); BlogFragment blog = new BlogFragment(); SportsFragment sports = new SportsFragment(); ScientistFragment scientistFragment = new ScientistFragment(); EconomicsFragment economicsFragment = new EconomicsFragment(); VideoFragment videoFragment = new VideoFragment(); EntertainmentFragment entertainmentFragment = new EntertainmentFragment(); ReadingFragment readingFragment = new ReadingFragment(); FemaleFragment femaleFragment = new FemaleFragment(); MaleFragment maleFragment = new MaleFragment(); MilitaryFragment militaryFragment = new MilitaryFragment(); CarsFragment carsFragment = new CarsFragment(); EducationFragment educationFragment = new EducationFragment(); HouseFragment houseFragment = new HouseFragment(); GamesFragment gamesFragment = new GamesFragment(); ConstellationFragment constellationFragment = new ConstellationFragment(); list.add(headLine); list.add(blog); list.add(sports); list.add(scientistFragment); list.add(economicsFragment); list.add(videoFragment); list.add(entertainmentFragment); list.add(readingFragment); list.add(femaleFragment); list.add(maleFragment); list.add(militaryFragment); list.add(carsFragment); list.add(educationFragment); list.add(houseFragment); list.add(gamesFragment); list.add(constellationFragment); } private View getTabItemView(int i){ View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.fragment_tabhost_content_main,null); TextView tv = (TextView) view.findViewById(R.id.tabhost_text); tv.setText(titles[i]); return view; } private class MainActivityFragmentPagerAdapter extends FragmentPagerAdapter{ public MainActivityFragmentPagerAdapter(FragmentManager fm){ super(fm); } @Override public Fragment getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } } } ``` activity_main.xml内容如下: ``` <?xml version="1.0" encoding="utf-8"?> <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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.wolfgy.news.newsclient.MainActivity"> <android.support.v4.app.FragmentTabHost android:id="@+id/main_fragmentTabHost" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v4.app.FragmentTabHost> <android.support.v4.view.ViewPager android:id="@+id/main_viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> </LinearLayout> ```

Fragment中怎样重新加载UI

Android中怎样重新调用Fragment的onCreateView函数,重新创建UI?

fragmentactivity中了用了办法来解决每次点击后重复加载ui,但是没效,求大神指教

package com.doone.changeverday.ui.fragmrnt; import java.util.ArrayList; import java.util.List; import com.doone.changeverday.R; import com.doone.changeverday_bean.ShopBean; import com.doone.changevryday.adpter.ShopAdpter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ListView; public class FragmentShoping extends Fragment { private View view; private View rooview;//用來判斷是否重複加載ui private ListView mListView; private List<ShopBean> mdata = new ArrayList<ShopBean>(); @Override @Nullable public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub if (rooview==null) { rooview = inflater.inflate(R.layout.fragment_shop, null); mListView = (ListView) rooview.findViewById(R.id.shop_list); } ViewGroup prent=(ViewGroup)rooview.getParent(); if (prent!=null) { prent.removeView(rooview); } return rooview; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); addData(); mListView.setAdapter(new ShopAdpter(mdata, getActivity())); } private void addData() { for (int i = 0; i < 3; i++) { ShopBean bean = new ShopBean(); bean.setStation("武侯區社區服務站"); bean.setStart("★★★★★"); bean.setMap("青羊區東大街16號"); mdata.add(bean); } } @Override public void onDestroyView() { super.onDestroyView(); ((ViewGroup)rooview.getParent()).removeView(rooview); } } ``` ```

求助!!!Fragment 里 添加一个Fragment 实现跳转出现空指针问题

```java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference ``` @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mBtnout = view.findViewById(R.id.btn_out); mTextgroup = view.findViewById(R.id.text_group); //设置适配器 listView = view.findViewById(R.id.list_item1); listView.setAdapter(new GroupAdapter(getActivity())); mBtnattend = view.findViewById(R.id.btn_attend); mBtnattend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().beginTransaction().replace(R.id.list_item1,partcipateFragment).commitAllowingStateLoss(); } }); 然后这个是布局文件 <?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"> <RelativeLayout android:padding="15dp" android:layout_width="match_parent" android:layout_height="70dp" android:background="#E8CA88"> <Button android:id="@+id/btn_out" android:layout_marginLeft="15dp" android:layout_marginTop="13dp" android:layout_width="15dp" android:layout_height="15dp" android:background="@drawable/fanhui"/> <TextView android:id="@+id/text_group" android:layout_marginTop="7dp" android:layout_centerHorizontal="true" android:textSize="20sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="xxx"/> </RelativeLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="bottom" android:orientation="horizontal"> <Button android:id="@+id/btn_group" android:layout_width="400dp" android:layout_height="40dp" android:text="xxx" android:layout_weight="1" android:background="#fff"/> <Button android:id="@+id/btn_attend" android:layout_weight="1" android:layout_width="400dp" android:layout_height="40dp" android:text="xxx" android:background="#fff"/> </LinearLayout> <LinearLayout android:id="@+id/li_list" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ListView android:id="@+id/list_item1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView> </LinearLayout> </LinearLayout> ```

在viewpager和fragment中嵌套listview,出现setAdapter空指针情况。

在viewpager和fragment中嵌套listview,出现setAdapter空指针情况。 为了实现滑动切换界面,我写了三个fragment,在一个fragment中加入了一个listview,怎么启动都是空指针。 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.example.tabhost_02.Fragment_Device.onActivityCreated(Fragment_Device.java:33) at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904) at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238) at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303) at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439) at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079) at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869) at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696) at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299) at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:235) at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244) at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092) at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:22002) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514) at android.widget.LinearLayout.measureVertical(LinearLayout.java:806) at android.widget.LinearLayout.onMeasure(LinearLayout.java:685) at android.view.View.measure(View.java:22002) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6580) at android.widget.FrameLayout.onMeasure(FrameLayout.java:185) at com.android.internal.policy.DecorView.onMeasure(DecorView.java:721) at android.view.View.measure(View.java:22002) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2410) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1498) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1751) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) at android.view.Choreographer.doCallbacks(Choreographer.java:723) at android.view.Choreographer.doFrame(Choreographer.java:658) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView5" android:layout_width="358dp" android:layout_height="wrap_content" android:text="状态详情" android:textColor="#000000" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="176dp" android:text="TextView" /> <TextView android:id="@+id/textView3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="部件信息" android:textColor="#000000" android:textSize="20sp" android:textStyle="bold" /> <TextView android:id="@+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="温度传感器" android:textColor="#2196F3" android:textSize="18sp" android:textStyle="bold" /> <ListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> public class Fragment_Device extends Fragment { private List<Info> infos = new ArrayList<>(); private ListView device_info=null; public Fragment_Device(){ } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_device, container, false); initInfo(); return view; } public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initInfo(); } private void initInfo() { Info dev_1 = new Info("室内环境监控", "20摄氏度", "100小时", "2019-05-01 09:00:00"); infos.add(dev_1); Info dev_2 = new Info("室内环境监控", "25摄氏度", "100小时", "2019-05-01 09:08:00"); infos.add(dev_2); Info dev_3 = new Info("室内环境监控", "23摄氏度", "100小时", "2019-05-01 10:00:00"); infos.add(dev_3); Info dev_4 = new Info("室内环境监控", "28摄氏度", "100小时", "2019-05-01 10:30:00"); infos.add(dev_4); InfoAdapter infoAdapter = new InfoAdapter(infos,getContext()); View view = LayoutInflater.from(getContext()).inflate(R.layout.list_item,null); infos=view.findViewById(R.id.lv); device_info = view.findViewById(R.id.lv); device_info.setAdapter(infoAdapter); } }

Fragment already added 接手别人的代码,出现这个问题,不知道如何 更改

接手别人的代码,出现这个问题,不知道如何改,求助。界面是有四个fragment,通过底部的四个图片切换四个fragment,出现这个问题,主要代码如下,求帮助: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); page_num = intent.getIntExtra("page_num", 0); setContentView(R.layout.main_activity); ButterKnife.inject(this); setSwipeBackEnable(false); queue = VolleyQuery.getQueue(this); intidrawable(); getLocal(); intiView(page_num); //设置导航点击方法 nav_mshop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { slider_animate(0); } }); nav_apply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { slider_animate(1); } }); nav_join.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { slider_animate(2); } }); nav_mine.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { slider_animate(3); } }); if (page_num == 0) { getNewVersion("auto"); } } //滑动动画&&选择fragment private void slider_animate(int postion) { for (int i = 0; i < 4; i++) { LinearLayout linearLayout = (LinearLayout) nav_container.getChildAt(i); TextView textView = (TextView) linearLayout.getChildAt(1); ImageView imageView = (ImageView) linearLayout.getChildAt(0); if (postion == i) { textView.setTextColor(getResources().getColorStateList(R.color.nav_text_pink)); imageView.setImageDrawable(drawables[i][0]); } else { textView.setTextColor(getResources().getColorStateList(R.color.nav_text_gra)); imageView.setImageDrawable(drawables[i][1]); } } if (mfilst.get(postion) == null) { switch (postion) { case 0: MshopFragment mshopFragment = new MshopFragment(); mfilst.put(postion, mshopFragment); break; case 1: ApplyFragment applyFragment = new ApplyFragment(); mfilst.put(postion, applyFragment); break; case 2: LeagueFragment leagueFragment = new LeagueFragment(); mfilst.put(postion, leagueFragment); break; case 3: MyFragment myFragment = new MyFragment(); mfilst.put(postion, myFragment); break; } } FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (!mfilst.get(postion).isAdded()) { try { fragmentTransaction.add(R.id.main_container, mfilst.get(postion), String.valueOf(postion)); } catch (Exception e) { e.printStackTrace(); } } for (int i = 0; i < 4; i++) { if (i != postion) { if (mfilst.get(i) != null && mfilst.get(i).isAdded()) { fragmentTransaction.hide(mfilst.get(i)); } } } fragmentTransaction.show(mfilst.get(postion)); fragmentTransaction.commit(); } boolean addList = false; @Override protected void onResume() { super.onResume(); this.addList = false; } @Override protected void onPause() { super.onPause(); } private void intiView(int page_num) { slider_animate(page_num); } private void intidrawable() { drawables[0][0] = getResources().getDrawable(R.mipmap.main_mshop_bottom_pink); drawables[0][1] = getResources().getDrawable(R.mipmap.main_mshop_bottom_gra); drawables[1][0] = getResources().getDrawable(R.mipmap.main_apply_bottom_pink); drawables[1][1] = getResources().getDrawable(R.mipmap.main_apply_bottom_gra); drawables[2][0] = getResources().getDrawable(R.mipmap.main_join_bottom_pink); drawables[2][1] = getResources().getDrawable(R.mipmap.main_join_bottom_gra); drawables[3][0] = getResources().getDrawable(R.mipmap.main_mine_bottom_pink); drawables[3][1] = getResources().getDrawable(R.mipmap.main_mine_bottom_gra); } 错误日志: Caused by: java.lang.IllegalStateException: Fragment already added: LeagueFragment{42e18a48 #1 id=0x7f0a00bb 2} at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1207) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:673) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4881) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575) at dalvik.system.NativeStart.main(Native Method)

android textview内容消失问题

我做了一个简单的fragment界面,主要是输入ID,然后向服务器查询内容后赋值回原来的界面上的textview,但是在运行的时候发生了一个奇怪的问题,一部分的textview消失了,具体很难描述,以下是整个过程的描述 ![图片说明](https://img-ask.csdn.net/upload/201605/14/1463197893_214757.jpg) 这是个原始界面,在最上方输入编号,然后查询。 ![图片说明](https://img-ask.csdn.net/upload/201605/14/1463197987_723570.jpg) 点击查询后,可以看见,背景内容已经加载,textview的内容已经进去了,但是加载完成后,textview ![图片说明](https://img-ask.csdn.net/upload/201605/14/1463198182_802396.jpg) 如上图,加载完成后,下面的Textview不见了,而且,连那些实现写好的静态的textview也不见了 然后,我通过弹出输入法,用输入法覆盖部分内容 ![图片说明](https://img-ask.csdn.net/upload/201605/14/1463198282_9279.jpg) 像上图这样,在搜索框中点击之后,输入法会自动弹出,覆盖掉下面的内容,然后再取消 ![图片说明](https://img-ask.csdn.net/upload/201605/14/1463198349_994971.jpg) 然后内容就出来了。。。 每次都是这个样子。。我觉得很奇怪,不知道什么原因导致的,谁能帮忙看看吗?谢谢 整个框架大框架是fragment+viewpage,查询用的AsyncTask查询后赋值。 上代码了,布局文件,是一个fragment_content,xml ``` <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:layout_width="270dip" android:layout_height="52dip" android:id="@+id/searchText" android:hint="请输入客户编号ID或扫二维码" android:background="@android:drawable/editbox_background_normal"/> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/ic_menu_search" android:id="@+id/search_button"/> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/ic_menu_camera" android:id="@+id/search_QRcode"/> </LinearLayout> <LinearLayout android:layout_marginTop="5dip" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#F2F3EB"> <TextView android:layout_width="360dip" android:layout_height="35dip" android:text="业主信息" android:gravity="center" android:layout_gravity="center" android:layout_marginTop="8dip" android:background="@android:drawable/btn_default" /> <LinearLayout android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="业主名称"/> <TextView android:id="@+id/CustomerNAME" android:layout_width="300dip" android:layout_height="wrap_content" android:text="请输入客户ID" android:gravity="center"/> </LinearLayout> <LinearLayout android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="行业性质"/> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/CustomerSegment"/> </LinearLayout> <LinearLayout android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="联系地址"/> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:id="@+id/CustomerAddress" android:gravity="center"/> </LinearLayout> <LinearLayout android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="联系人"/> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:id="@+id/CustomerContactor" android:gravity="center"/> </LinearLayout> <LinearLayout android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="联系电话"/> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:id="@+id/CustomerPhone" android:gravity="center"/> </LinearLayout> <LinearLayout android:layout_marginLeft="4dip" android:layout_marginTop="8dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="5dip"> <TextView android:layout_width="100dip" android:layout_height="wrap_content" android:gravity="center" android:text="保养合约到期时间"/> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:id="@+id/Customercontactdate" android:gravity="center"/> </LinearLayout> //下面开始就是出问题的部分布局 </LinearLayout> <LinearLayout android:layout_marginTop="10dip" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#F2F3EB"> <TextView android:layout_width="360dip" android:layout_height="35dip" android:text="维护人员信息" android:gravity="center" android:layout_gravity="center" android:layout_marginTop="8dip" android:background="@android:drawable/btn_default" /> <TextView android:layout_width="400dip" android:layout_height="30dip" android:text="专属客户代表" android:gravity="center" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="10dip"> <ImageView android:layout_width="120dip" android:layout_height="100dip" android:src="@drawable/unknownpic" android:id="@+id/SRPIC"/> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="姓名" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/ServiceRepresentive" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="职位" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/SRP" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="联系方式" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/SRN" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="工作年限" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/SRY" android:gravity="center"/> </TableRow> </TableLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="400dip" android:layout_height="30dip" android:text="专属服务技师" android:gravity="center" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginBottom="10dip"> <ImageView android:layout_width="120dip" android:layout_height="100dip" android:src="@drawable/unknownpic" android:id="@+id/STPIC"/> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="姓名" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/ServiceTechnician" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="职位" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/STN" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="工作年限" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/STY" android:gravity="center"/> </TableRow> <TableRow android:layout_marginTop="7dip"> <TextView android:layout_width="70dip" android:layout_height="wrap_content" android:text="专业技能" android:gravity="center"/> <TextView android:layout_width="220dip" android:layout_height="match_parent" android:id="@+id/STS" android:gravity="center"/> </TableRow> </TableLayout> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </ScrollView> ``` fragment的文件,里面除了查询,还有一个二维码扫描 ``` public class CustomerInf extends Fragment { ImageButton search,search_QRcode; EditText editText; String searchID; TextView CustomerName,CustomerSegment,CustomerAddress,CustomerContactor,CustomerPhone; TextView Customercontactdate,ServiceRepresentive,SRP,SRN,SRY,ServiceTechnician,STN,STY,STS; ImageView SRPIC,STPIC; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_content, container, false); bind(view); return view; } //对各内容进行绑定 public void bind(View view) { search = (ImageButton) view.findViewById(R.id.search_button); editText = (EditText) view.findViewById(R.id.searchText); CustomerName=(TextView)view.findViewById(R.id.CustomerNAME); CustomerSegment=(TextView)view.findViewById(R.id.CustomerSegment); CustomerAddress=(TextView)view.findViewById(R.id.CustomerAddress); CustomerContactor=(TextView)view.findViewById(R.id.CustomerContactor); CustomerPhone=(TextView)view.findViewById(R.id.CustomerPhone); Customercontactdate=(TextView)view.findViewById(R.id.Customercontactdate); ServiceRepresentive=(TextView)view.findViewById(R.id.ServiceRepresentive); SRP=(TextView)view.findViewById(R.id.SRP); SRN=(TextView)view.findViewById(R.id.SRN); SRY=(TextView)view.findViewById(R.id.SRY); ServiceTechnician=(TextView)view.findViewById(R.id.ServiceTechnician); STN=(TextView)view.findViewById(R.id.STN); STY=(TextView)view.findViewById(R.id.STY); STS=(TextView)view.findViewById(R.id.STS); SRPIC=(ImageView) view.findViewById(R.id.SRPIC); STPIC=(ImageView) view.findViewById(R.id.STPIC); search.setOnClickListener(new Click()); search_QRcode=(ImageButton)view.findViewById(R.id.search_QRcode); search_QRcode.setOnClickListener(new QRsearch()); } //此处是一个引用外部二维码扫描的程序 public class QRsearch implements View.OnClickListener{ @Override public void onClick(View v){ if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) { } else { requestPermissions( new String[]{Manifest.permission.CAMERA}, 123); } } else { Toast.makeText(getContext(),"开始扫描",Toast.LENGTH_SHORT).show(); Intent startScan=new Intent(getContext(), CaptureActivity.class); startActivityForResult(startScan, Activity.RESULT_FIRST_USER); } } } //二维码的返回 @Override public void onActivityResult(int requestCode,int resultCode,Intent data){ super.onActivityResult(requestCode,resultCode,data); if(resultCode==Activity.RESULT_OK){ Bundle bundle = data.getExtras(); String scanResult = bundle.getString("result"); editText.setText(scanResult); searchID = editText.getText().toString().trim(); if (TextUtils.isEmpty(searchID)) { Toast.makeText(getActivity(), "请输入客户ID"+searchID, Toast.LENGTH_LONG).show(); } else { SearchTask searchTask = new SearchTask(); String[] array=new String[]{"http://www.klmt001.com/CustomerINF.php",searchID}; searchTask.execute(array); } } } //这里是查询按钮的监听器 public class Click implements View.OnClickListener { @Override public void onClick(View v) { searchID = editText.getText().toString().trim(); if (TextUtils.isEmpty(searchID)) { Toast.makeText(getActivity(), "请输入客户ID"+searchID, Toast.LENGTH_LONG).show(); } else { SearchTask searchTask = new SearchTask(); String[] array=new String[]{"http://www.klmt001.com/CustomerINF.php",searchID}; searchTask.execute(array); } } } //监听按钮的AsyncTask class SearchTask extends AsyncTask<String, Integer, JSONObject> { ProgressDialog p1; @Override protected void onPreExecute() { p1=new ProgressDialog(getActivity()); p1.setTitle("请等待"); p1.setMessage("等待中........"); p1.setCancelable(false); p1.show(); new Handler().postDelayed(new Runnable(){ public void run() { p1.dismiss(); } }, 1000); } protected JSONObject doInBackground(String... inf) { HttpClient httpclient = new DefaultHttpClient(); HttpEntity entity = null; StringBuilder builder = new StringBuilder(); JSONObject jsonObject=null; try { HttpPost httpPost = new HttpPost(inf[0]); List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("CustomerID", inf[1])); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpPost); entity = response.getEntity(); if (response.getEntity() != null) { if (response.getEntity().toString().equals("0")) { jsonObject=null; Log.v("msg",""+"没有收到信息"); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String s = reader.readLine(); for (; s != null; s = reader.readLine()) { builder.append(s); } Log.v("msg",""+"成功获取信息"); jsonObject = new JSONObject(builder.toString()); } } } catch (Exception E) { Log.e("msg", E.getMessage()); Log.v("msg", "没有成功 "); } finally { try { if (entity != null) { // entity.consumeContent();//强制释放资源 httpclient.getConnectionManager().shutdown();//关闭连接 //这两种释放连接的方法都可以 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return jsonObject; } //获取值之后开始对原来的textview进行赋值 protected void onPostExecute(JSONObject webcontent){ String cn,cs,ca,cc,cp,cd,sr,srd,srn,sry,st,stn,sty,sts,pic1,pic2; if(webcontent==null){ Toast.makeText(getActivity(),"没有对应的客户信息",Toast.LENGTH_LONG).show(); }else { try { cn=webcontent.getString("CustomerName"); CustomerName.setText(cn); cs=webcontent.getString("CustomerSegment"); CustomerSegment.setText(cs); ca=webcontent.getString("CustomerAddress"); CustomerAddress.setText(ca); cc=webcontent.getString("CustomerContactor"); CustomerContactor.setText(cc); cp=webcontent.getString("CustomerPhone"); CustomerPhone.setText(cp); cd=webcontent.getString("Customercontactdate"); Customercontactdate.setText(cd); sr=webcontent.getString("ServiceRepresentive"); ServiceRepresentive.setText(sr); srd=webcontent.getString("SRP"); SRP.setText(srd); srn=webcontent.getString("SRN"); SRN.setText(srn); sry=webcontent.getString("SRY"); SRY.setText(sry); st=webcontent.getString("ServiceTechnician"); ServiceTechnician.setText(st); stn=webcontent.getString("STN"); STN.setText(stn); sty=webcontent.getString("STY"); STY.setText(sty); sts=webcontent.getString("STS"); STS.setText(sts); pic1=webcontent.getString("SRPIC"); pic2=webcontent.getString("STPIC"); String[] pics=new String[]{pic1,pic2}; Loadpics loadpics=new Loadpics(); loadpics.execute(pics); }catch (Exception E){ E.printStackTrace(); } } } } //这里是用来获取图片的 class Loadpics extends AsyncTask<String, Integer, Bitmap[]>{ protected Bitmap[] doInBackground(String... inf) { Bitmap[] bitmaps=new Bitmap[2]; Bitmap bitmap1,bitmap2; try{ URL url1=new URL(inf[0]); URLConnection conn1=url1.openConnection(); conn1.connect(); InputStream inputStream = conn1.getInputStream(); bitmap1 = BitmapFactory.decodeStream(inputStream); URL url2=new URL(inf[1]); URLConnection conn2=url2.openConnection(); conn2.connect(); InputStream inputStream2 = conn2.getInputStream(); bitmap2 = BitmapFactory.decodeStream(inputStream2); bitmaps[0]=bitmap1; bitmaps[1]=bitmap2; }catch (Exception E){ Log.e("msg", E.getMessage()); }return bitmaps; } protected void onPostExecute(Bitmap[] bitmap){ try{ SRPIC.setImageBitmap(bitmap[0]); STPIC.setImageBitmap(bitmap[1]); }catch (Exception E){ Log.e("msg", E.getMessage()); } } }} ```

android Listview(第一项未滑出屏幕)自动回到顶部

一个诡异的现象: viewpager里面放三个Fragment,每个Fragment里面是个listview,如下三张图 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506064425_798150.jpg) ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506064604_263028.jpg) ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506064645_654924.jpg) 下面开始操作,第一个Fragment里,listview上滑一点(**第一个item不滑出屏幕**)如下图 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506064835_340669.jpg) 这时候切换到第三个Fragment后,再返回至第一个,这时候的第一个Fragment 变成了在最顶部的位置,如下图 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506064425_798150.jpg) **诡异现象来了**, 操作 第一个Fragment里,listview上滑至**第一个item滑出屏幕**,如下图 ![图片说明](https://img-ask.csdn.net/upload/201709/22/1506065043_657575.jpg) 再做上面的切换步骤后,返回第一个Fragment **保持的位置是不变的**; viewPager使用的是FragmentStatePagerAdapter,如果会有销毁视图的情况发生,那为什么 listview上滑至**第一个item滑出屏幕** 后位置是不变的, 代码就不贴了,都是基础的listview.setAdapter() ,listview每一项里就放了个textView, 不知道有什么办法可以一直保持着listview的位置

求指导,谢谢各位大神。 ViewPager和FragmentPagerAdapter实现切换,但是无法显示数据

**想做个应用市场,效果如图,下面的是一级标签,用的TabHost跳转Activity实现。然后上面这一排是二级标签,想用TextView + ViewPager + Fragment 实现,现在滑动有效,但是数据加载不出来。求指教,捉急一整天了。 ![CSDN移动问答][1] ![CSDN移动问答][2] 这是“推荐”对应的Activity:** public class CommendActivity extends FragmentActivity { private static final int INDEX_COM = 0; private static final int INDEX_NEW = 1; private static final int INDEX_HOT = 2; private static final int INDEX_GUESS = 3; private ImageView comPointer; // 指针 private TextView comCom, comNew, comHot, comGuess; // 标签 private ViewPager comPager; private PagerAdapter pagerAdapter; private List<CommendFragment> fragments; private int currentPage = 0; // 当前二级页 private int delta = 0; // 指针单位移动量 private int offset = 0; // 指针移动偏移值 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_commend); initPointer(); initTextView(); initViewPager(); } /* * 配置标签 */ private void initTextView() { comCom = (TextView) findViewById(R.id.comCom); comNew = (TextView) findViewById(R.id.comNew); comHot = (TextView) findViewById(R.id.comHot); comGuess = (TextView) findViewById(R.id.comGuess); comClickListener listener = new comClickListener(); comCom.setOnClickListener(listener); comNew.setOnClickListener(listener); comHot.setOnClickListener(listener); comGuess.setOnClickListener(listener); } /* * 配置标签指针 */ private void initPointer() { comPointer = (ImageView) findViewById(R.id.comPointer); int imageWidth = BitmapFactory.decodeResource(getResources(), R.drawable.pointer).getWidth(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); delta = dm.widthPixels / 4; offset = (delta - imageWidth) / 2; Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); comPointer.setImageMatrix(matrix); } /* * 配置ViewPager */ private void initViewPager() { comPager = (ViewPager) findViewById(R.id.comPager); fragments = new ArrayList<CommendFragment>(); CommendFragment comFragment = CommendFragment.newInstance(INDEX_COM); CommendFragment newFragment = CommendFragment.newInstance(INDEX_NEW); CommendFragment hotFragment = CommendFragment.newInstance(INDEX_HOT); CommendFragment guessFragment = CommendFragment.newInstance(INDEX_GUESS); fragments.add(comFragment); fragments.add(newFragment); fragments.add(hotFragment); fragments.add(guessFragment); comPager.setAdapter(new TabsAdapter(getSupportFragmentManager(), fragments)); comPager.setCurrentItem(currentPage); comPager.setOnPageChangeListener(new ComPageChangeListener()); } private class comClickListener implements OnClickListener { @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.comCom: comPager.setCurrentItem(INDEX_COM); break; case R.id.comNew: comPager.setCurrentItem(INDEX_NEW); break; case R.id.comHot: comPager.setCurrentItem(INDEX_HOT); break; case R.id.comGuess: comPager.setCurrentItem(INDEX_GUESS); break; } } } private class ComPageChangeListener implements OnPageChangeListener { @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { Toast.makeText( CommendActivity.this, "this is " + ((TabsAdapter)comPager.getAdapter()).getItem(position), Toast.LENGTH_SHORT) .show(); Animation anim = new TranslateAnimation(delta * currentPage, delta * position, 0, 0); currentPage = position; anim.setFillAfter(true); anim.setDuration(300); comPointer.startAnimation(anim); } } } **Adapter的java代码:** public class TabsAdapter extends FragmentPagerAdapter { private List<CommendFragment> fragments; public TabsAdapter(FragmentManager fm, List<CommendFragment> list) { super(fm); this.fragments = list; } @Override public int getCount() { return fragments.size(); } @Override public boolean isViewFromObject(View view, Object obj) { return view == obj; } @Override public Fragment getItem(int position) { return fragments.get(position); } } **Fragment的java代码:** public class CommendFragment extends Fragment { private static final int DEFAULT_TAG = -1; private int tag; private TextView tv; /** * 添加标识,返回带标识的对象。 * * @param tag * 标识 * @return 带标识的Fragment */ public static CommendFragment newInstance(int tag) { CommendFragment fragment = new CommendFragment(); Bundle b = new Bundle(); b.putInt("tag", tag); fragment.setArguments(b); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle b = getArguments(); tag = (null == b ? DEFAULT_TAG : b.getInt("tag")); } /** * 解析布局 */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_com, container, false); tv = (TextView) view.findViewById(R.id.empty); tv.setText(tv.getText().toString() + tag); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } } [1]: http://img1.ph.126.net/fxzDnnu6ODkwAVCuK-bChw==/6597399620146971619.jpg [2]: http://img1.ph.126.net/0I9zg-8JmaTJ7aOhFH3cvw==/1929792440428526119.jpg

android 上滑下滑标题切换效果实现。

![图片说明](https://img-ask.csdn.net/upload/201602/24/1456285723_151445.jpg) 如图所示,它不是像viewpager一样的切换是4个fragment,是整个一个页面,滑动到对应的区域标题就跟着切换,点击标题也能切换到对应的区域,因为最底下是评论,我发现有上拉加载功能,所以个人认为用的是整个一个pulltorefreshlistview,根据listview中的type判断的?具体是如何实现呢,还有那个点击滑动到对应区域的效果,希望大神能给与解答。

viewpager抢子控件焦点

如图,一个viewpager嵌套3个fragment,第一个fragment里面有一个listview,item中有一个imageview,在listview的adapter中设置imageview的点击事件,弹出一个popuwindow,第一次进入这个fragment中时,点击imageview响应点击事件,响应一次之后,再点击,无反应,然后稍微滑动viewpager或者点击一下listview的条目的时候,imageview的点击事件才响应,debug也是,应该是焦点问题,但具体的我不知道,有哪位大神帮我看看,应该改哪里 ![图片说明](https://img-ask.csdn.net/upload/201707/05/1499248558_405255.png)

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

C++11:一些微小的变化(新的数据类型、template表达式内的空格、nullptr、std::nullptr_t)

本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

深入剖析Springboot启动原理的底层源码,再也不怕面试官问了!

大家现在应该都对Springboot很熟悉,但是你对他的启动原理了解吗?

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

【阿里P6面经】二本,curd两年,疯狂复习,拿下阿里offer

二本的读者,在老东家不断学习,最后逆袭

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

微软为一人收购一公司?破解索尼程序、写黑客小说,看他彪悍的程序人生!...

作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

我说我懂多线程,面试官立马给我发了offer

不小心拿了几个offer,有点烦

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

立即提问
相关内容推荐