有 TabLayout 和 ViewPager 的嵌套 fragment 。每个 fragment 内部都有 ListView ,因此它们可以一起调用,现在我遇到了应用程序处理速度慢的问题。我尝试了一些解决方案,例如 volley library,但它对我不起作用。有关更多信息,我也发布了我的代码,所以请指导我做到最好。
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1;
int position_tab = 0;
Bundle args;
MyTabLayout myTabLayout;
public MainTabFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
NonSiwpablePager pager = (NonSiwpablePager) view.findViewById(R.id.pager);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(4);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
@Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
@Override
public Fragment getItem(int position) {
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
@Override
public int getCount() {
return maps.size();
}
}
}
MainTabFragment 的子 fragment 为:
AdvisoryPagerFragment.java
public class AdvisoryPagerFragment extends Fragment {
static String advisory_child_fragments[];
int myID = 0;
Bundle bundle;
TabLayout mTabLayout;
public AdvisoryPagerFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment AdvisoryPagerFragment.
*/
public static AdvisoryPagerFragment newInstance() {
return new AdvisoryPagerFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_app_pager, container, false);
/*Bundle args = getArguments();
if (args != null && args.containsKey("pos_end"))
myID = args.getInt("pos_end");*/
myID = MainTabFragment.position_child_tab;
mTabLayout = (TabLayout) inflate.findViewById(R.id.fragmentTabLayout);
advisory_child_fragments = new String[]{"EQUITY", "INDICES", "COMMODITY", "CURRENCY"};
ViewPager pager = (ViewPager) inflate.findViewById(R.id.fragment_pager);
FragmentViewPagerAdapter mPagerAdapter = new FragmentViewPagerAdapter(getChildFragmentManager());
pager.setAdapter(mPagerAdapter);
mTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
View customView = mPagerAdapter.getCustomeView(getActivity(), i);
mTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(myID);
return inflate;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTabLayout.getTabAt(myID).getCustomView().setSelected(true);
}
public static class FragmentViewPagerAdapter extends FragmentStatePagerAdapter {
public FragmentViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.belowTab_textview);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
mTextView.setText(getPageTitle(pos));
return mView;
}
//
@Override
public CharSequence getPageTitle(int position) {
return advisory_child_fragments[position];
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new EquityFragment();
case 1:
return new IndicesFragment();
case 2:
return new CommodityFragment();
case 3:
return new CurrencyFragment();
}
return null;
}
@Override
public int getCount() {
return 4;
}
}
}
而上述AdvisoryPagerFragment的子 fragment 是
EquityFragment.java
public class EquityFragment extends android.support.v4.app.Fragment implements SearchView.OnQueryTextListener {
public static String imagepath = null;
static ArrayList<EquityDetails> catListDao = new ArrayList<EquityDetails>();
static ArrayList<EquityDetails> catListDao1 = new ArrayList<EquityDetails>();
static int count = 0;
static int count1 = 0;
ListView list;
View view;
Activity act;
AdvisorsAdapter adapter;
TextView empty_text;
private boolean isViewShown = false;
ProgressBar progressBar;
public static EquityFragment newInstance() {
return new EquityFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.equity_activity, container, false);
act = this.getActivity();
Log.d("Callled ", "" + count);
count++;
return view;
}
public void onActivityCreated(Bundle savedInstanceState1) {
super.onActivityCreated(savedInstanceState1);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
list = (ListView) view.findViewById(R.id.list_equity);
setHasOptionsMenu(true);
empty_text = (TextView) view.findViewById(R.id.empty);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
if (Utils.isNetworkAvailable(getActivity())) {
if (catListDao.size() > 0) {
adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 5);
list.setAdapter(adapter);
} else {
new Thread(new Runnable() {
@Override
public void run() {
// do some work here
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// if (!isViewShown) {
new FetchAllData(getActivity(), 5).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// }
}
});
}
}).start();
}
} else {
CustomToast toast = new CustomToast(getActivity(), "There is no internet connection!");
}
}
FetchdataClass 从服务中获取数据并添加到 ListView
public class FetchAllData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
int typeId;
private Context cont;
public FetchAllData(Context con, int typeId) {
// TODO Auto-generated constructor stub
this.cont = con;
this.typeId = typeId;
Log.d("Constructor Called", "yes");
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
return getString();
}
private String getString() {
// TODO Auto-generated method stub
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL(Constants.AppBaseUrl + "/call_listing/" + typeId);
String userPassword = "oi" + ":" + "kl";
String header = "Basic " + new String(android.util.Base64.encode(userPassword.getBytes(), android.util.Base64.NO_WRAP));
con = (HttpURLConnection) obj.openConnection();
con.addRequestProperty("Authorization", header);
con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.i("TAG", response.toString());
return response.toString();
} else {
Log.i("TAG", "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
// pDialog.dismiss();
progressBar.setVisibility(View.GONE);
JSONObject jsonObject;
try {
catListDao = new ArrayList<EquityDetails>();
jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("list");
Log.d("Length ", "" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
EquityDetails allDirectory = new EquityDetails();
allDirectory.setEntry_value(jsonArray.getJSONObject(i).getString("entry"));
allDirectory.setSerial_value(jsonArray.getJSONObject(i).getString("sl"));
allDirectory.setTg_value1(jsonArray.getJSONObject(i).getString("tgt_1"));
allDirectory.setTg_value2(jsonArray.getJSONObject(i).getString("tgt_2"));
allDirectory.setMainTitle_value(jsonArray.getJSONObject(i).getString("script"));
allDirectory.setMain_subTitle_value(jsonArray.getJSONObject(i).getString("exchange"));
allDirectory.setRating_value(jsonArray.getJSONObject(i).getString("rating"));
allDirectory.setReview_value(jsonArray.getJSONObject(i).getString("review"));
allDirectory.setImage1(jsonArray.getJSONObject(i).getString("advisor_image"));
allDirectory.setPosted_by(jsonArray.getJSONObject(i).getString("posted_by"));
allDirectory.setImage2(jsonArray.getJSONObject(i).getString("script_image"));
allDirectory.setCall_id(jsonArray.getJSONObject(i).getString("call_id"));
allDirectory.setBuy(jsonArray.getJSONObject(i).getString("buy_sentiment"));
allDirectory.setSell(jsonArray.getJSONObject(i).getString("sell_sentiment"));
allDirectory.setRecommend(jsonArray.getJSONObject(i).getString("recommendation"));
allDirectory.setPosted_date(jsonArray.getJSONObject(i).getString("posted_date"));
allDirectory.setExpiry_date(jsonArray.getJSONObject(i).getString("expiry_date"));
catListDao.add(allDirectory);
}
catListDao1 = catListDao;
ab = true;
adapter = new AdvisorsAdapter(act, R.layout.custom_equity, catListDao, 0);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
//pDialog.dismiss();
progressBar.setVisibility(View.GONE);
}
}
最佳答案
尝试设置
pager.setOffscreenPageLimit(no_of_fragments or pages);
在创建 fragment 时在 asyctask 中完成所有任务
关于Android ViewPager 和 TabLayout 运行不快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015117/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/
GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'
是否有可能:before_filter:authenticate_user!||:authenticate_admin! 最佳答案 before_filter:do_authenticationdefdo_authenticationauthenticate_user!||authenticate_admin!end 关于ruby-on-rails-before_filter运行多个方法,我们在StackOverflow上找到一个类似的问题: https://
之前在培训新生的时候,windows环境下配置opencv环境一直教的都是网上主流的vsstudio配置属性表,但是这个似乎对新生来说难度略高(虽然个人觉得完全是他们自己的问题),加之暑假之后对cmake实在是爱不释手,且这样配置确实十分简单(其实都不需要配置),故斗胆妄言vscode下配置CV之法。其实极为简单,图比较多所以很长。如果你看此文还配不好,你应该思考一下是不是自己的问题。闲话少说,直接开始。0.CMkae简介有的人到大二了都不知道cmake是什么,我不说是谁。CMake是一个开源免费并且跨平台的构建工具,可以用简单的语句来描述所有平台的编译过程。它能够根据当前所在平台输出对应的m
有没有一种简单的方法可以判断ruby脚本是否已经在运行,然后适本地处理它?例如:我有一个名为really_long_script.rb的脚本。我让它每5分钟运行一次。当它运行时,我想看看之前运行的是否还在运行,然后停止第二个脚本的执行。有什么想法吗? 最佳答案 ps是一种非常糟糕的方法,并且可能会出现竞争条件。传统的Unix/Linux方法是将PID写入文件(通常在/var/run中)并在启动时检查该文件是否存在。例如pid文件位于/var/run/myscript.pid然后你会在运行程序之前检查它是否存在。有一些技巧可以避免
我正在尝试使用以下代码通过将ffmpeg实用程序作为子进程运行并获取其输出并解析它来确定视频分辨率:IO.popen'ffmpeg-i'+path_to_filedo|ffmpegIO|#myparsegoeshereend...但是ffmpeg输出仍然连接到标准输出并且ffmepgIO.readlines是空的。ffmpeg实用程序是否需要一些特殊处理?或者还有其他方法可以获得ffmpeg输出吗?我在WinXP和FedoraLinux下测试了这段代码-结果是一样的。 最佳答案 要跟进mouviciel的评论,您需要使用类似pope