在 viewpager 中如何实现 Button 的 onClick 方法

我想在viewpaper中,点击按钮弹出Toast信息,并且想知道如何在viewpaper上访问views?
我用的以下的代码,不好用。

public class MyPagerAdapter extends PagerAdapter {

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public Object instantiateItem(final View collection, final int position) {
         v = new View(collection.getContext());
        LayoutInflater inflater =
                (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.cate1;
            v = inflater.inflate(R.layout.cate1, null, false);
            add1 = (Button) v.findViewById(R.id.btnAdd);
            add1.setOnClickListener( new OnClickListener() {
                public void onClick(View m) {
                   Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show();
                }
            });


            break;
        case 1:
            resId = R.layout.cate2;
            break;
        case 2:
            resId = R.layout.cate3;
            break;
        }

        View view = inflater.inflate(resId, null);
        ((ViewPager) collection).addView(view, 0);

        return view;
    }

    @Override
    public void destroyItem(final View arg0, final int arg1, final Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);

    }

    @Override
    public boolean isViewFromObject(final View arg0, final Object arg1) {
        return arg0 == ((View) arg1);

    }

    @Override
    public void finishUpdate(View arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public Parcelable saveState() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void startUpdate(View arg0) {
        // TODO Auto-generated method stub

    }
        }

下面是 button onclick代码,也没有实现

v = inflater.inflate(R.layout.cate1, null, false);
            add1 = (Button) v.findViewById(R.id.btnAdd);
            add1.setOnClickListener( new OnClickListener() {
                public void onClick(View m) {
                   Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show();
                }
            });

请求大家的帮忙,看看如何处理这个问题。

2个回答

把你代码中的

((ViewPager) collection).addView(view, 0);

    return view;

改为

((ViewPager) collection).addView(v, 0);

    return v;

参考github.com/Shereef/ViewPagerPlusExpandableList ,可以很好的理解viewpager。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
在 viewpager 中如何创建 button onClick 方法
我想使用viewpager在按钮点击时Toast一个消息,也想了解更多关于如何访问viewpager中的视图的信息。用的以下的信息,没什么反应。 public class MyPagerAdapter extends PagerAdapter { @Override public int getCount() { return 3; } @Override public Object instantiateItem(final View collection, final int position) { v = new View(collection.getContext()); LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); int resId = 0; switch (position) { case 0: resId = R.layout.cate1; v = inflater.inflate(R.layout.cate1, null, false); add1 = (Button) v.findViewById(R.id.btnAdd); add1.setOnClickListener( new OnClickListener() { public void onClick(View m) { Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show(); } }); break; case 1: resId = R.layout.cate2; break; case 2: resId = R.layout.cate3; break; } View view = inflater.inflate(resId, null); ((ViewPager) collection).addView(view, 0); return view; } @Override public void destroyItem(final View arg0, final int arg1, final Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(final View arg0, final Object arg1) { return arg0 == ((View) arg1); } @Override public void finishUpdate(View arg0) { // TODO Auto-generated method stub } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { // TODO Auto-generated method stub } @Override public Parcelable saveState() { // TODO Auto-generated method stub return null; } @Override public void startUpdate(View arg0) { // TODO Auto-generated method stub } } 然后用下面的代码实现button onclick方法,也不对。 v = inflater.inflate(R.layout.cate1, null, false); add1 = (Button) v.findViewById(R.id.btnAdd); add1.setOnClickListener( new OnClickListener() { public void onClick(View m) { Toast.makeText(collection.getContext(),"click",Toast.LENGTH_LONG).show(); } }); add1.setOnClickListener 不能执行,也没有报错。总之,想要实现的button action 没有执行。是什么问题呢?
viewpager 点击事件的响应
如何在viewpager 中的主Activity中得到其他页面的Button public class MainActivity extends Activity { private LinearLayout indexLayout; private ImageView[] indexViews=new ImageView[4]; private ViewPager vp; private View[] views=new View[4]; private Button btn3; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initIndex(); vp=(ViewPager)findViewById(R.id.viewPager); views[0]=getLayoutInflater().inflate(R.layout.page1, null); views[1]=getLayoutInflater().inflate(R.layout.page2, null); views[2]=getLayoutInflater().inflate(R.layout.page3, null); views[3]=getLayoutInflater().inflate(R.layout.page4, null); ViewPagerAdapter adapter=new ViewPagerAdapter(); vp.setAdapter(adapter); ViewPager.OnPageChangeListener listener=new ViewPager.OnPageChangeListener() { public void onPageSelected(int arg0) { System.out.println("onPageSelected"); for(ImageView iv:indexViews){ iv.setBackgroundResource(R.drawable.present); } indexViews[arg0].setBackgroundResource(R.drawable.santa); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } }; vp.setOnPageChangeListener(listener); } class ViewPagerAdapter extends PagerAdapter{ public int getCount() { return views.length; } public boolean isViewFromObject(View arg0, Object arg1) { return arg0==arg1; } @Override public void destroyItem(View container, int position, Object object) { ((ViewPager)container).removeView(views[position]); } @Override public Object instantiateItem(View container, int position) { ((ViewPager)container).addView(views[position]); return views[position]; } } private void initIndex() { indexLayout=(LinearLayout)findViewById(R.id.indexLayout); for(int i=0;i<4;++i){ indexViews[i]=new ImageView(this); } indexViews[0].setBackgroundResource(R.drawable.santa); indexViews[0].setLayoutParams(new LayoutParams(25,25)); for(int i=1;i<=3;++i){ indexViews[i].setBackgroundResource(R.drawable.present); indexViews[i].setLayoutParams(new LayoutParams(25,25));//width,height } for(int i=0;i<4;++i){ indexLayout.addView(indexViews[i]); } } }
viewpager里面Button点击传值错误
每个页面点击Button的时候传出去的id值都是16。 请问怎么才能每个页面点击按钮的时候分别传出去当前页面的值。1,3,7,16 ....... private int[] a = {1, 3, 7, 16}; 根据a的长度加载viewpager页数 for (int i=0; i<a.length; i++) { id = a[i]; ...... view = LayoutInflater.from(this).inflate(R.layout.viewpager_item, null); Button more = (Button) view.findViewById(R.id.more); more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(My.this, Detials.class); intent.putExtra("position", id + ""); startActivity(intent); } }); ...... }
Button onClick事件不能运行
我创建一个viewPager,在每一个页面上有三个布局。在第二个页面上我想处理按钮事件,当点击按钮时背景颜色会变。但是现在我的代码不能运行。去掉button代码,viewPager就可以正常运行。 这是我的代码: public class ViewPagerProjectActivity extends Activity implements OnClickListener{ Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ViewPagerAdapter adapter = new ViewPagerAdapter( this ); ViewPager pager = (ViewPager)findViewById( R.id.viewpager ); pager.setAdapter( adapter ); pager.setCurrentItem(0); } public void OnClick(View v) { if(v.equals(btn)) { LinearLayout l = (LinearLayout) findViewById(R.id.deneme2); l.setBackgroundDrawable(getResources().getDrawable(R.drawable.background)); } } } 错误: E/AndroidRuntime(273): FATAL EXCEPTION: main E/AndroidRuntime(273): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yahya.ViewPagerProject/com.yahya.ViewPagerProject.ViewPagerProjectActivity}: java.lang.ClassCastException: com.yahya.ViewPagerProject.ViewPagerProjectActivity E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
Android中viewpager内部子控件Imagebutton问题
大家好,最近做了一个小项目,用到了viewpager,我没有用最新的fragment来布置每一个页面,而是采用传统的方法,inflater加载了几个view,这样我的事件都集中在了mainactivity中,我在其中一个页面中布置了一个imagebutton,并在mainactivity中对其进行了初始化,然后给他添加了一个onclick方法,在这个方法内部,我想用setImageResource来修改image button的背景,但总是出现空指针,请问这个问题怎么解决呢?
viewpager如何动态删除fragment
private ViewPager viewPager; /** 页面list **/ ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); @Override public void onCreate(Bundle savedInstanceState) { viewPager = (ViewPager)findViewById(R.id.viewPager); TextView titleTextView; titleTextView = (TextView) this.findViewById(R.id.title_text); Intent intent = getIntent(); String id = intent.getStringExtra("id"); String title = intent.getStringExtra("title"); titleTextView.setText(title); addFragmentToViewPager(id,title,null,"1"); viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), fragmentList)); viewPager.setOnPageChangeListener(new MyOnPageChangeListener()); viewPager.setOnTouchListener(new MyOnTouchListener()); Button titleleftButton=(Button)findViewById(R.id.title_bt_left); titleleftButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //处理删除 int w=fragmentList.size(); if(w==1){ finish(); }else{ fragmentList.remove(w-1).onDestroy(); viewPager.setCurrentItem(w-2); Log.i("bctt",fragmentList.size()+""); } } }); //添加一个fragment到viewpager private void addFragmentToViewPager(String id, String title, String sql, String FragmentName) { Fragment CardListFragment; CardListFragment = new CardListFragment(); CardListFragment.setArguments(args); fragmentList.add(CardListFragment); viewPager.setCurrentItem(fragmentList.indexOf(CardListFragment)); 想动态添加删除fragment到viewpager,不知道如何实现,很急,请知道的同学帮忙看一下 还有一个问题,如何去除viewpager左右滑动,这样我可以通过一个按钮点击,一级一级的删除fragment
使用viewpager,fragment底栏导航,新的fragment替换旧的fragment
主activity public class MyActivity extends FragmentActivity { private ViewPager mViewPager; private IconTabPageIndicator mIndicator; List<BaseFragment> fragments; Button LoginButton; LayoutInflater inflater; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bmob.initialize(this, "d77a8e1ebfd8e187cbc814145918626d"); //requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_my); mViewPager = (ViewPager) findViewById(R.id.view_pager); mIndicator = (IconTabPageIndicator) findViewById(R.id.indicator); fragments =new ArrayList<BaseFragment>(); BaseFragment planFragment = new BaseFragment(); planFragment.setTitle("计划"); planFragment.setIconId(R.drawable.tab_plan_selector); //BaseFragment writeFragment = new BaseFragment(); Fragment01 writeFragment=new Fragment01(); writeFragment.setTitle("记账"); writeFragment.setIconId(R.drawable.tab_write_selector); Fragment02 recordFragment = new Fragment02(); recordFragment.setTitle("账单"); recordFragment.setIconId(R.drawable.tab_record_selector); Fragment03 userFragment = new Fragment03(); userFragment.setTitle("用户"); userFragment.setIconId(R.drawable.tab_user_selector); fragments.add(writeFragment); fragments.add(planFragment); fragments.add(recordFragment); fragments.add(userFragment); FragmentAdapter adapter = new FragmentAdapter(fragments,getSupportFragmentManager()); mViewPager.setAdapter(adapter); mIndicator.setViewPager(mViewPager); } **fragment03.java** fragment03中有一个button,下面是onclick消息,在点击按钮是怎样把fragment03加载成新的fragment??? class MyButton implements View.OnClickListener { public void onClick(View v){ edit_username = (EditText)view.findViewById(R.id.userNameText) ; edit_password = (EditText)view.findViewById(R.id.passwdText) ; string_username = edit_username.getText().toString();//登录账号 string_password = edit_password.getText().toString();//登录密码 //云验证 BmobQuery<login> bmobQuery= new BmobQuery<login>();; bmobQuery.addWhereEqualTo("username",string_username); bmobQuery.addWhereEqualTo("password",string_password); bmobQuery.findObjects(getActivity(), new FindListener<login>() { @Override public void onSuccess(List<login> list) { for (login gameScore : list) { //获得playerName的信息 gameScore.getUsername(); gameScore.getPassword(); //Toast.makeText(getActivity(),gameScore.getUsername()+gameScore.getPassword(), Toast.LENGTH_SHORT).show(); //切换fragment 出错??? Fragment newFragment = new Fragment01(); FragmentTransaction transaction =getFragmentManager().beginTransaction(); transaction.replace(R.id.view_pager,newFragment); transaction.commit(); } } public void onError(int i, String s) { Toast.makeText(getActivity(), "登录失败 ", Toast.LENGTH_SHORT).show(); //Log.v("test","登录失败"); } }); } } 用viewpager加fragment实现了底栏切换fragment,在某个fragment怎样重新加载fragment,某个fragment是登录功能,登录成功要加载用户信息,也就是新的fragment。怎么实现?在onCreateView中? ![图片说明](https://img-ask.csdn.net/upload/201604/15/1460718920_546782.png)
使用 android-support-v4.jar 如何禁用 ViewPager swiping?
我在2.2版本上创建了一个 android 应用程序,想使用 android.support-v4.jar 中的 ViewPager,实现在点击按钮时,禁用 Viewpager swipping。 我使用下面的代码但是没有成功 public class ServiesDeail extends FragmentActivity{ ServiesTitleFragmentAdapter mAdapter; ViewPager mPager; int position = 0 ; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mastermenu); LinearLayout lnrparent = (LinearLayout) findViewById(R.id.LL_001); LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.menu_deatil, null); lnrparent.addView(view); mAdapter = new ServiesTitleFragmentAdapter(getSupportFragmentManager()); mPager = (ViewPager) findViewById(R.id.pagerone); mPager.setAdapter(mAdapter); TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicatorone); indicator.setViewPager(mPager,position); Menu_Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPager.setClickable(false); } }); } } 如何实现这个功能呢?
动态更新布局失败,想在图片中添加button进去。
package com.example.viewpager; import java.util.ArrayList; import com.example.fragment2.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class ViewpagerActivity extends Activity implements OnClickListener, OnPageChangeListener { //定义ViewPager对象 private ViewPager viewPager; //定义ViewPager适配器 private ViewPagerAdapter vpAdapter; //定义一个ArrayList来存放View private ArrayList<View> views; //引导图片资源 private static final int[] pics={R.drawable.guide1,R.drawable.guide2,R.drawable.guide3,R.drawable.guide4}; //底部小点的图片 private ImageView[] points; //记录当前选中位置 private int currentIndex; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.viewpagerlayout); initView(); initData(); } /** * 初始化组件 */ private void initView() { //实例化ArrayList对象 views=new ArrayList<View>(); //实例化ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager); //实例化ViewPager适配器 vpAdapter=new ViewPagerAdapter(views); } /** * 初始化数据 */ private void initData() { //定义一个布局并设置参数 LinearLayout.LayoutParams mParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); //初始化引导图片列表 for(int i=0;i<pics.length;i++) { ImageView iv=new ImageView(this); //在最后一张引导页中加入button按钮方便进入主界面 if(i==pics.length-1) { RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); Button button=new Button(this); button.setText("立即体验"); button.setTextSize(24); params=(RelativeLayout.LayoutParams)button.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); button.setLayoutParams(params); //使layout更新 iv.setLayoutParams(params); iv.setImageResource(pics[i]); }else{ iv.setLayoutParams(mParams); iv.setImageResource(pics[i]); } views.add(iv); } //设置数据 viewPager.setAdapter(vpAdapter); //设置监听 viewPager.setOnPageChangeListener(this); //初始化底部小点 initPoint(); } /** * 初始化底部小点 */ private void initPoint() { LinearLayout linearLayout=(LinearLayout)findViewById(R.id.pointlayout); points=new ImageView[pics.length]; //循环获得小点图片 for(int i=0;i<pics.length;i++) { //得到一个LinearLayout下面的每一个子元素 points[i]=(ImageView)linearLayout.getChildAt(i); //默认都为灰色 points[i].setEnabled(true); //给每个小点设置监听 points[i].setOnClickListener(this); //设置位置tag,方便取出与当前位置对应 points[i].setTag(i); } //设置当前默认的位置 currentIndex=0; } /** * 当滑动状态改变时调用 * */ @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub //设置底部小点选中状态 setCurDot(arg0); } /** * 设置当前页面的位置 */ private void setCurView(int position) { if(position<0||position>=pics.length) { return; } viewPager.setCurrentItem(position); } /** * 设置当前的小点的位置 */ private void setCurDot(int position) { if(position<0||position>pics.length-1||currentIndex==position) { return; } points[position].setEnabled(false); points[currentIndex].setEnabled(true); currentIndex=position; } /** * 通过点击事件来切换当前的页面 */ @Override public void onClick(View v) { // TODO Auto-generated method stub int position =(Integer)v.getTag(); setCurView(position); setCurDot(position); } } ![图片说明](https://img-ask.csdn.net/upload/201608/06/1470414709_246575.png)
Android中怎样用自定义的adapter加载日期列表
想实现以下的效果,因为自己技术大白,不知道怎么处理,贴出代码: 我是用ViewPager + Fragment实现页面切换的,其中在fragmentB中有个按钮button,fragmentA中有个listview,现在想实现的是,通过点击B中的button,在A中的listview中显示一个item,item的名字用当前时间来设置。我用的是自定义的adapter, ``` private class DateAdapter extends ArrayAdapter<Date_item> { private int resourceId; public DateAdapter(Context context, int dateresourceId, List<Date_item> objects){ super(context, dateresourceId,objects); resourceId = dateresourceId; } @Override public View getView(int position,View convertView, ViewGroup parent){ Date_item date_item = getItem(position);//获取当前项的date实例 View view; ViewHolder viewHolder; if(convertView == null){ view = LayoutInflater.from(getContext()).inflate(resourceId,null); viewHolder = new ViewHolder(); viewHolder.date = (TextView)view.findViewById(R.id.chart_date); view.setTag(viewHolder);//将viewHolder缓存到view中 }else { view = convertView; viewHolder = (ViewHolder)view.getTag(); } return view; } class ViewHolder{ TextView date; } } ``` 我将A中列表的item也设置在了B中: ``` //列表item的时间形式 //设置时间格式 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss"); //获取当前时间 long time = System.currentTimeMillis(); //将long转化为Date Date date = new Data(time); String timeSave = format.format(date); ``` 在B中的button的监听事件里面: ``` btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ DateAdapter dateAdapter =new DateAdapter(getActivity(),R.layout.item_layout,dateList); listView.setAdapter(dateAdapter); } }) ``` 程序一运行就闪退,错误是NullPointerException:Attempt to invoke virtual method'void android widget.ListView.setAdapter(android.widget.ListAdapter)'on a null object reference. 请问这是什么情况,这问题困了我很久了,在线等,感谢各位
ViewPager+Fragment+ListView启动后第一个页面是空白,怎么改进解决?
ViewPager+Fragment(4个)+ListView启动后第一个页面是空白。 首先说明的是当listview里面的adapter不用callback的方法获取json的时候,一切都是正常的。 当4个fragment中只有一个listview的时候,用callback方法也是正常的,但是两个fragement中都有listview的时候,比如fragment1 & fragment2中各有一个listview,然后每个都callback就不行了,但是滑动一下,有时就可以了。 先说目录结构:MainActivity ,fragmentone,fragmentone2... 上代码: package com.example.viewpagerdemo; import java.util.ArrayList; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; import com.example.viewpagerdemo.myadapter.MyFragmentPagerAdapter; public class MainActivity extends FragmentActivity implements OnClickListener, OnPageChangeListener { private ViewPager mViewPager; private Button bt_list1, bt_list2, bt_list3, bt_list4; private ArrayList<Fragment> list = null; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mainwin); mContext=MainActivity.this; initView(); initEvent(); } private void initView() { mViewPager = (ViewPager) findViewById(R.id.vpager); bt_list1 = (Button) findViewById(R.id.button1); bt_list2 = (Button) findViewById(R.id.button2); bt_list3 = (Button) findViewById(R.id.button3); bt_list4 = (Button) findViewById(R.id.button4); fragmentone fg1 = new fragmentone(); fragmenttwo fg2 = new fragmenttwo(); fragmentthree fg3 = new fragmentthree(); fragmentfour fg4 = new fragmentfour(); list = new ArrayList<Fragment>(); list.add(fg1); list.add(fg2); list.add(fg3); list.add(fg4); mViewPager.setAdapter(new MyFragmentPagerAdapter( getSupportFragmentManager(), list)); } private void initEvent() { mViewPager.setCurrentItem(0); bt_list1.setOnClickListener(this); bt_list2.setOnClickListener(this); bt_list3.setOnClickListener(this); bt_list4.setOnClickListener(this); mViewPager.setOnPageChangeListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: mViewPager.setCurrentItem(0); Toast.makeText(mContext, "当前选择:1",Toast.LENGTH_SHORT).show(); break; case R.id.button2: mViewPager.setCurrentItem(1); Toast.makeText(mContext, "当前选择:2",Toast.LENGTH_SHORT).show(); break; case R.id.button3: mViewPager.setCurrentItem(2); Toast.makeText(mContext, "当前选择:3",Toast.LENGTH_SHORT).show(); break; case R.id.button4: mViewPager.setCurrentItem(3); Toast.makeText(mContext, "当前选择:4",Toast.LENGTH_SHORT).show(); break; } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onResume() { // TODO Auto-generated method stub mViewPager.setCurrentItem(1); mViewPager.setCurrentItem(0); super.onResume(); } @Override public void onPageScrollStateChanged(int state) { // TODO Auto-generated method stub if (state==2) { Toast.makeText(mContext, "当前选择:"+(mViewPager.getCurrentItem()+1),Toast.LENGTH_SHORT).show(); } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub //Toast.makeText(mContext, "当前选择:"+mViewPager.getCurrentItem(),Toast.LENGTH_SHORT); } } fragmentone: package com.example.viewpagerdemo; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toast; import com.example.viewpagerdemo.myCallBack.HttpUtil; import com.example.viewpagerdemo.myCallBack.ResultCallback; import com.example.viewpagerdemo.myadapter.ListAdapterOne; import com.example.viewpagerdemo.mybean.BaseBean; import com.example.viewpagerdemo.mybean.BeanOneArrayList; import com.example.viewpagerdemo.mybean.ListBeanOne; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * fragment 1 * * @author dy * */ public class fragmentone extends Fragment { private Context mContext; private View viewOne; private ListView mListViewOne; private List<ListBeanOne> allDataOne; private ListAdapterOne oneAdapter; private ResultCallback callback = new ResultCallback() { @Override public void getReslt(String result) { // TODO Auto-generated method stub BaseBean b = HttpUtil.getData(mContext, result, "", ""); if (b.getResponsecode() == 1) { Type type = new TypeToken<BeanOneArrayList>() { }.getType(); Gson gson = new Gson(); BeanOneArrayList json = gson.fromJson(result, type); allDataOne = json.getData(); if (allDataOne.size() > 0) { oneAdapter = new ListAdapterOne(mContext, allDataOne); mListViewOne.setAdapter(oneAdapter); /* * Message message = new Message(); message.what=1; * mHandler.sendMessage(message); */ } else { Log.i("tag", "No Data"); } } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (viewOne != null) { ViewGroup parentViewGroup = (ViewGroup) viewOne.getParent(); if (parentViewGroup != null) { parentViewGroup.removeAllViewsInLayout(); } } else { viewOne = inflater.inflate(R.layout.fg1, container, false); } initView(); initEvent(); return viewOne; } private void initView() { mContext = this.getActivity(); mListViewOne = (ListView) viewOne.findViewById(R.id.listView1); } private void initEvent() { String JsonURL = AppConst.ListURL1; List<NameValuePair> p = new ArrayList<NameValuePair>(); p.add(new BasicNameValuePair("action", "1")); HttpUtil.doPost(JsonURL, p, callback); } } fragmenttwo: package com.example.viewpagerdemo; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.example.viewpagerdemo.myCallBack.HttpUtil; import com.example.viewpagerdemo.myCallBack.ResultCallback; import com.example.viewpagerdemo.myadapter.ListAdapterOne; import com.example.viewpagerdemo.myadapter.ListAdapterTwo; import com.example.viewpagerdemo.mybean.BaseBean; import com.example.viewpagerdemo.mybean.BeanTwoArrayList; import com.example.viewpagerdemo.mybean.ListBeanTwo; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * fragment 2 * * @author dy * */ public class fragmenttwo extends Fragment { private Context mContext; private View viewTwo; private ListView mListViewTwo; private List<ListBeanTwo> allDataTwo; private ListAdapterTwo twoAdapter; private ResultCallback callback = new ResultCallback() { @Override public void getReslt(String result) { // TODO Auto-generated method stub BaseBean b = HttpUtil.getData(mContext, result, "", ""); if (b.getResponsecode() == 1) { Type type = new TypeToken<BeanTwoArrayList>() { }.getType(); Gson gson = new Gson(); BeanTwoArrayList json = gson.fromJson(result, type); allDataTwo = json.getData(); if (allDataTwo.size() > 0) { twoAdapter = new ListAdapterTwo(mContext, allDataTwo); mListViewTwo.setAdapter(twoAdapter); /* * Message message = new Message(); message.what=1; * mHandler.sendMessage(message); */ } else { Log.i("tag", "No Data"); } } } }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (viewTwo != null) { ViewGroup parentViewGroup = (ViewGroup) viewTwo.getParent(); if (parentViewGroup != null) { parentViewGroup.removeAllViewsInLayout(); } } else { viewTwo = inflater.inflate(R.layout.fg2, container, false); } initView(); initEvent(); return viewTwo; } private void initView() { mContext = this.getActivity(); mListViewTwo = (ListView) viewTwo.findViewById(R.id.listView2); } private void initEvent() { String JsonURL = AppConst.ListURL1; List<NameValuePair> p = new ArrayList<NameValuePair>(); p.add(new BasicNameValuePair("action", "2")); HttpUtil.doPost(JsonURL, p, callback); } } MyFragmentPagerAdapter: package com.example.viewpagerdemo.myadapter; import java.util.ArrayList; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private ArrayList<Fragment> list; public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> list) { super(fm); this.list = list; } @Override public Fragment getItem(int arg0) { // TODO Auto-generated method stub return list.get(arg0); } @Override public int getCount() { // TODO Auto-generated method stub return list.size(); } } ``` ``` 其他的代码都是类似的,就不发了。 ``` ```
Android PagerAdapter里面的NullPointException
是这样的,我做了一个实现ViewPager的程序,包含两个View页面; 我在其中一个View页面中添加了Button按钮,然后在MainActivity里面写Button点击 事件的时候总是没有响应,然后在网上查了一下说应该在PagerAdapter的instantiateItem方法里面实例化Button然后写响应事件,下面是我的代码: ``` public Object instantiateItem(ViewGroup container, int position) { switch (position) { case 1: musicName = (EditText) theList.get(position).findViewById( R.id.musicname_edittext); singerName = (EditText) theList.get(position).findViewById( R.id.singername_edittext); Button searchButton = (Button) theList.get(position).findViewById( R.id.search_button); Button resetButton = (Button) theList.get(position).findViewById( R.id.reset_button); // 搜索按钮点击事件 searchButton.setOnClickListener(new OnClickListener() { // 通过用户输入的歌名和歌手名获取url,通过url获取xml文件输入流,然后sax解析xml输入流 @Override public void onClick(View v) { // TODO Auto-generated method stub String urlString = getUrl(); GetInputStreamAsyncTask getInputTask = new GetInputStreamAsyncTask(); getInputTask.execute(urlString); inputStream = getInputTask.getInputStream(); saxParseXML(inputStream); } }); // 重置按钮点击事件 resetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub musicName.setText(""); singerName.setText(""); } }); break; default: break; } container.addView(theList.get(position), 0); return theList.get(position); } ``` 我在一个Button响应事件中想使用AsyncTask获取网络上一个xml文件的InputStream,然后用sax解析这个InputStream,下面是我的AsycTask类的代码: ```public class GetInputStreamAsyncTask extends AsyncTask<String, Integer, Boolean>{ private InputStream inputStream; public GetInputStreamAsyncTask(){ } public InputStream getInputStream() { return inputStream; } @Override protected Boolean doInBackground(String... params) { // TODO Auto-generated method stub DownloadDataByUrl dl=new DownloadDataByUrl(); try { inputStream=dl.getInputStreamFromUrl(params[0]); byte[] b = new byte[1024]; StringBuilder sb = new StringBuilder(); int len = -1; try { while ((len = inputStream.read(b)) != -1) { sb.append(new String(b, 0, len)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("xiaoqiang:" + sb); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } ``` 可以看到我在doInBackGround方法里面获取InputStream后进行了输出操作,而且运行程序后输出了完整的xml文件字符,如下: ![图片说明](https://img-ask.csdn.net/upload/201507/20/1437407420_269505.png) 这个是logcat的错误信息,我在 getInputTask.execute(urlString); 语句后面调用了System.out.println()输出语句成功。但是在saxParseXML(inputStream);语句之前调用System.out.println()输出语句失败。 ![图片说明](https://img-ask.csdn.net/upload/201507/20/1437407573_37315.png) 调试了一整天也没有找出问题所在,求解~~
动态的使用Fragment,底部四个按钮的布局怎么写
原文链接http://blog.csdn.net/lmj623565791/article/details/37970961 我是这样写的但是选中底部的按钮后无效果 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:baselineAligned="false" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/tab_bottom_weixin" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button1" android:onClick="onClick" > </Button> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/tab_bottom_friend"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button2" android:onClick="onClick"> </Button> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button3"> </Button> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button4"> </Button> </LinearLayout> <android.support.v4.view.ViewPager android:id="@+id/vPager" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1.0" android:background="#000000" android:flipInterval="30" android:persistentDrawingCache="animation" /> </LinearLayout>
Android下拉列表刷新不出来
页面切换是用的Fragment+ViewPager来完成的,三个页面,SaveFragment,ShowFragment,SetFragment,现在在SaveFragment中设置了一个下拉刷新列表,想实现在ShowFragment中的Button点击,将数据保存,并在Save界面下拉刷新出列表,列表即Button点击保存的数据。这对于我来说挺难的,求大神指点,运行程序的时候总是不出现列表。代码贴出: ``` ShowFragment中的button点击事件的处理: btnSave.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Log.i(TAG,"执行数据保存操作!"); getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ MainActivity mainActivity = (MainActivity)getActivity(); SaveFragment saveFragment = mainActivity.getSaveFragment(); //打算让列表以当前时间的名字的形式保存。 //设置时间格式 SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd/HH:mm:ss"); //获取当前时间 long time = System.currentTimeMillis(); //将long转化为Date Date date = new Date(time); String timeSave = format.format(date); Log.i(TAG,"timeSave = " + timeSave); if(saveFragment != null){ saveFragment.addDateForList(timeSave); saveFragment.notifyDataSetChanged(); Log.d(TAG,"date has been saved."); } } }) } }); ``` 两个fragment都已经在MainActivity中声明了, ``` 下拉刷新列表的代码如下,我感觉问题在这里,但是我不知道怎么改: RefreshableView refreshableView = (RefreshableView)view.findViewById(R.id.refreshable_view); refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener(){ @Override public void onRefresh(){ try{ //我觉得应该在try里面添加时间,但是不知道怎么去添加。。。 Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } refreshableView.finishRefreshing(); } },0); public void addDateForList(String date){ dateList.add(date); } public void notifyDataSetChanged(){ dateAdapter.notifyDataSetChanged(); } ``` 这是用到的主要的代码,程序运行的时候,用log来查看运行的情况的时候, if里面的log并没有打印出来,不知道怎么修改 ``` if(saveFragment != null){ saveFragment.addDateForList(timeSave); saveFragment.notifyDataSetChanged(); Log.d(TAG,"date has been saved."); } ``` 安卓自学小白一枚,求大神路过指教啊~
findviewbyid 空指针的问题
各位大侠,最近发现一个问题个人觉得非常诡异。 在oncreate 中 listView_test = (ListView) this.findViewById(R.id.listcardinfo); 为null。 但是 同一个页面中的一个button的 onClick方法确可以找到这个listview,并且赋值。 附上XML ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:umadsdk="http://schemas.android.com/apk/res/com.LoveBus" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:orientation="vertical" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试" android:textColor="#000000" android:textSize="22.0dip" /> <include layout="@layout/home_title_layout"/> </RelativeLayout> <android.support.v4.view.ViewPager android:id="@+id/vPager" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:layout_weight="1.0" android:flipInterval="30" android:persistentDrawingCache="animation" /> </LinearLayout> ``` ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <ListView android:id="@+id/listcardinfo" android:layout_width="fill_parent" android:layout_height="fill_parent" > </ListView> </LinearLayout> ```
安卓,可循环滑动的图片,不显示标示哪张图的小点,求大神来帮忙
contentmain.xml: ``` <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main" tools:context=".MainActivity"> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent"/> <LinearLayout android:id="@+id/viewgroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center_horizontal" android:layout_marginBottom="10dp"></LinearLayout> </FrameLayout> ``` 定义点状图标的drawable的xml,以下是选中的,没选中的也就颜色不一样: ``` <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:color="#ff6666" android:shape="ring"> <corners android:radius="20dp" /> </shape> ``` viewpager是用fragment填充的,fragment里也就一个imageButton,不贴了 以下是MainActivity: ``` public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener { List<Fragment> list; ViewPager viewPager; ViewGroup viewGroup; Fragment1 f1=new Fragment1(); Fragment1 p1=new Fragment1(); Fragment2 f2=new Fragment2(); Fragment3 f3=new Fragment3(); Fragment4 f4=new Fragment4(); Fragment4 p4=new Fragment4(); MyAdapter myAdapter; ImageView[] imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); list=new ArrayList<Fragment>(); list.add(p4); list.add(f1); list.add(f2); list.add(f3); list.add(f4); list.add(p1); viewPager=(ViewPager)super.findViewById(R.id.viewpager); viewGroup=(ViewGroup)super.findViewById(R.id.viewgroup); initViewGroup(); myAdapter=new MyAdapter(getSupportFragmentManager(),list); viewPager.setAdapter(myAdapter); viewPager.setCurrentItem(1); viewPager.setOnPageChangeListener(this); } @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); } public void initViewGroup() { imageView=new ImageView[list.size()-3]; for(int i=0;i<list.size()-3;i++) { imageView[i] = new ImageView(this); if(i==1) imageView[i].setBackgroundResource(R.drawable.select); else imageView[i].setBackgroundResource(R.drawable.unselect); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); params.leftMargin = 10; params.rightMargin = 10; viewGroup.addView(imageView[i], params); } } @Override public void onPageScrollStateChanged(int args0) { } public void onPageSelected(int args0) { int pageIndex=args0; if(pageIndex==0) { pageIndex=list.size()-2; imageView[0].setBackgroundResource(R.drawable.unselect); imageView[imageView.length-1].setBackgroundResource(R.drawable.select); } else if(pageIndex==list.size()-1) { pageIndex=1; imageView[imageView.length-1].setBackgroundResource(R.drawable.unselect); imageView[0].setBackgroundResource(R.drawable.select); } if(pageIndex != args0) { viewPager.setCurrentItem(pageIndex, false); } } public void onPageScrolled(int a1,float a2,int a3) { } } ``` 想做那种图片可循环滑动,并且其底部有小点标示是哪张图的效果,现在图片能循环滑,但是不显示小点,希望各位大神帮忙看看
求助求助,特别简单的问题,在滑动的时候上面的按钮不变化,但是点击按钮就变化
下面是我Fragment的代码 ``` package textview.exam; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import java.util.ArrayList; import java.util.List; public class FragmentChat extends Fragment { private ArrayList<Fragment> fragmentlist; private ViewPager mviewpager; private View viewbar; private int currIndex;//当前页卡编号 private List<RadioButton> listViews; /* private RadioGroup main_chat_newsRedio; private FragmentMainchatnews main_chat_news; private FragmentMainchattrends main_chat_trends; private FragmentMainchatweather main_chat_weather;*/ @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.main_chat, null); initView(view); InitViewPager(view); return view; } //初始化标签 private void initView(View view) { RadioButton pager1 = (RadioButton)view. findViewById(R.id.main_chat_news); RadioButton pager2 = (RadioButton) view.findViewById(R.id.main_chat_trends); RadioButton pager3 = (RadioButton) view.findViewById(R.id.main_chat_weather); listViews = new ArrayList<RadioButton>(); listViews.add(pager1); listViews.add(pager2); listViews.add(pager3); pager1.setOnClickListener(new txListner(0)); pager2.setOnClickListener(new txListner(1)); pager3.setOnClickListener(new txListner(2)); } //监听页面切换 private class txListner implements View.OnClickListener { private int index = 0; public txListner (int i){ index = i; } public void onClick(View v){ mviewpager.setCurrentItem(index); } } /* * 初始化ViewPager */ public void InitViewPager(View view){ mviewpager = (ViewPager)view.findViewById(R.id.id_viewpager); fragmentlist = new ArrayList<Fragment>(); Fragment OneFragment = new FragmentMainchatnews(); Fragment TwoFragment = new FragmentMainchattrends(); Fragment ThreeFragment = new FragmentMainchatweather(); fragmentlist.add(OneFragment); fragmentlist.add(TwoFragment); fragmentlist.add(ThreeFragment); //给ViewPager设置适配器 mviewpager.setAdapter(new MyFragmentPagerAdapter(getChildFragmentManager(), fragmentlist)); mviewpager.setCurrentItem(0);//设置当前显示标签页为第一页 mviewpager.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器 } public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int arg0, float arg1, int arg2) { if(currIndex==arg0) { RadioButton pager1 = (RadioButton) getView().findViewById(R.id.main_chat_news); pager1.setTextColor(Color.WHITE); }else if(currIndex==arg1){ RadioButton pager2 = (RadioButton) getView().findViewById(R.id.main_chat_trends); pager2.setTextColor(Color.WHITE); }else{ RadioButton pager3 = (RadioButton) getView().findViewById(R.id.main_chat_weather); pager3.setTextColor(Color.WHITE); } } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageSelected(int arg0) { currIndex = arg0; } } } ``` 下面是我xml中的代码 ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.exam.Activity"> <RadioGroup android:id="@+id/chat_tab_menu" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FF0066" android:orientation="horizontal" > <RadioButton android:id="@+id/main_chat_news" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_weight="1" android:button="@null" android:checked="true" android:height="140px" android:gravity="center" android:paddingTop="2dp" android:text="新闻" android:textColor="@color/tab_selector_tv_color" /> <RadioButton android:id="@+id/main_chat_trends" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_weight="1" android:button="@null" android:height="140px" android:gravity="center" android:paddingTop="2dp" android:text="动态" android:textColor="@color/tab_selector_tv_color" /> <RadioButton android:id="@+id/main_chat_weather" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="bottom" android:layout_weight="1" android:button="@null" android:height="140px" android:gravity="center" android:paddingTop="2dp" android:text="天气" android:textColor="@color/tab_selector_tv_color" android:checked="false" /> </RadioGroup> <android.support.v4.view.ViewPager android:id="@+id/id_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:flipInterval="30" android:persistentDrawingCache="animation" android:layout_below="@+id/chat_tab_menu" /> </RelativeLayout> ``` 求大神
新手请教android底部导航栏问题
andriod底部导航栏每当移到第一个时就报错,出现空指针异常,希望哪位大神能指教一下,到底哪错了 错误信息: 09-29 22:09:21.098: E/AndroidRuntime(863): java.lang.NullPointerException 09-29 22:09:21.098: E/AndroidRuntime(863): at com.example.producer.MainActivity$MyOnPageChangeListener.onPageSelected(MainActivity.java:240) java文件: package com.example.producer; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Toast; public class MainActivity extends Activity { public static MainActivity instance = null; private ViewPager mTabPager; private ImageView mTabImg;// 动画图片 private ImageView mTab1,mTab2,mTab3,mTab4,mTab5; private int currIndex = 0;// 当前页卡编号 private int zero = 0;// 动画图片偏移量 private int one;//单个水平动画位移 private int two; private int three; private int four; private LinearLayout mClose; private LinearLayout mCloseBtn; private View layout; private boolean menu_display = false; private PopupWindow menuWindow; private LayoutInflater inflater; //private Button mRightBtn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //启动activity时不自动弹出软键盘 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); instance = this; /* mRightBtn = (Button) findViewById(R.id.right_btn); mRightBtn.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { showPopupWindow (MainWeixin.this,mRightBtn); } });*/ mTab1 = (ImageView) findViewById(R.id.img_weixin); mTab2 = (ImageView) findViewById(R.id.img_address); mTab3 = (ImageView) findViewById(R.id.img_friends); mTab4 = (ImageView) findViewById(R.id.img_settings); mTab5 = (ImageView) findViewById(R.id.img_settings2); mTabImg = (ImageView) findViewById(R.id.img_tab_now); mTab1.setOnClickListener(new MyOnClickListener(0)); mTab2.setOnClickListener(new MyOnClickListener(1)); mTab3.setOnClickListener(new MyOnClickListener(2)); mTab4.setOnClickListener(new MyOnClickListener(3)); mTab5.setOnClickListener(new MyOnClickListener(4)); Display currDisplay = getWindowManager().getDefaultDisplay();//获取屏幕当前分辨率 int displayWidth = currDisplay.getWidth(); int displayHeight = currDisplay.getHeight(); one = displayWidth/5; //设置水平动画平移大小 two = one*2; three = one*3; four = one*4; //Log.i("info", "获取的屏幕分辨率为" + one + two + three + "X" + displayHeight); mTabPager = (ViewPager)findViewById(R.id.tabpager); mTabPager.setOnPageChangeListener(new MyOnPageChangeListener()); //InitImageView();//使用动画 //将要分页显示的View装入数组中 LayoutInflater mLi = LayoutInflater.from(this); View view1 = mLi.inflate(R.layout.test2, null); View view2 = mLi.inflate(R.layout.trip, null); View view3 = mLi.inflate(R.layout.firstpage, null); View view4 = mLi.inflate(R.layout.activity_help, null); View view5 = mLi.inflate(R.layout.home_page, null); //每个页面的view数据 final ArrayList<View> views = new ArrayList<View>(); views.add(view1); views.add(view2); views.add(view3); views.add(view4); views.add(view5); //填充ViewPager的数据适配器 PagerAdapter mPagerAdapter = new PagerAdapter() { @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return views.size(); } @Override public void destroyItem(View container, int position, Object object) { ((ViewPager)container).removeView(views.get(position)); } //@Override //public CharSequence getPageTitle(int position) { //return titles.get(position); //} @Override public Object instantiateItem(View container, int position) { ((ViewPager)container).addView(views.get(position)); return views.get(position); } }; mTabPager.setAdapter(mPagerAdapter); } /** * 头标点击监听 */ public class MyOnClickListener implements View.OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } public void onClick(View v) { mTabPager.setCurrentItem(index); } }; /* 页卡切换监听(原作者:D.Winter) */ public class MyOnPageChangeListener implements OnPageChangeListener { public void onPageSelected(int arg0) { Animation animation = null; switch (arg0) { case 0: mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_weixin_pressed)); if (currIndex == 1) { animation = new TranslateAnimation(one, 0, 0, 0); mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_address_normal)); } else if (currIndex == 2) { animation = new TranslateAnimation(two, 0, 0, 0); mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_find_frd_normal)); } else if (currIndex == 3) { animation = new TranslateAnimation(three, 0, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } else if (currIndex == 5) { animation = new TranslateAnimation(three, four, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } break; case 1: mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_address_pressed)); if (currIndex == 0) { animation = new TranslateAnimation(zero, one, 0, 0); mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_weixin_normal)); } else if (currIndex == 2) { animation = new TranslateAnimation(two, one, 0, 0); mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_find_frd_normal)); } else if (currIndex == 3) { animation = new TranslateAnimation(three, one, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } else if (currIndex == 5) { animation = new TranslateAnimation(one, four, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } break; case 2: mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_find_frd_pressed)); if (currIndex == 0) { animation = new TranslateAnimation(zero, two, 0, 0); mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_weixin_normal)); } else if (currIndex == 1) { animation = new TranslateAnimation(one, two, 0, 0); mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_address_normal)); } else if (currIndex == 3) { animation = new TranslateAnimation(three, two, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } else if (currIndex == 5) { animation = new TranslateAnimation(two, four, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } break; case 3: mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_pressed)); if (currIndex == 0) { animation = new TranslateAnimation(zero, three, 0, 0); mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_weixin_normal)); } else if (currIndex == 1) { animation = new TranslateAnimation(one, three, 0, 0); mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_address_normal)); } else if (currIndex == 2) { animation = new TranslateAnimation(two, three, 0, 0); mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_find_frd_normal)); } else if (currIndex == 5) { animation = new TranslateAnimation(three, four, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } break; case 4: mTab5.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_pressed)); if (currIndex == 0) { animation = new TranslateAnimation(zero, four, 0, 0); mTab1.setImageDrawable(getResources().getDrawable(R.drawable.tab_weixin_normal)); } else if (currIndex == 1) { animation = new TranslateAnimation(one, four, 0, 0); mTab2.setImageDrawable(getResources().getDrawable(R.drawable.tab_address_normal)); } else if (currIndex == 2) { animation = new TranslateAnimation(two, four, 0, 0); mTab3.setImageDrawable(getResources().getDrawable(R.drawable.tab_find_frd_normal)); } else if (currIndex == 3) { animation = new TranslateAnimation(three, four, 0, 0); mTab4.setImageDrawable(getResources().getDrawable(R.drawable.tab_settings_normal)); } break; } // currIndex = arg0; animation.setFillAfter(true);// True:图片停在动画结束位置 animation.setDuration(200);//检索或设置对象动画的持续时间 mTabImg.startAnimation(animation); } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageScrollStateChanged(int arg0) { } } }
android工程导包之后总是错误,错误提示附在图片上,有大神愿意帮忙解决一下吗?
package com.szitu.myapplication1.androidteris; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.szitu.myapplication1.Bmob.PlayerData; import com.szitu.myapplication1.R; import com.szitu.myapplication1.constant.Constant; import com.szitu.myapplication1.httputil.CRecord; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.listener.CountListener; import cn.bmob.v3.listener.FindListener; public class CustomRecord extends BaseActivity{ public ArrayList<PlayerData> cRecords = new ArrayList<PlayerData>(); public ArrayList<PlayerData> cthreeRecords = new ArrayList<PlayerData>(); public CRecord cRecordRank; public ListView recordList; public ViewPager viewpager; public View record; public View rank; public ArrayList<View> viewList; public TextView userName; public TextView userRank; public TextView userScore; public TextView num1Name; public TextView num1Rank; public TextView num1Score; public TextView num2Name; public TextView num2Rank; public TextView num2Score; public TextView num3Name; public TextView num3Rank; public TextView num3Score; public Button cancel; public Button logout; Handler handle = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if(msg.what==1){ recordList.setAdapter( new RecordList()); }else if(msg.what==2){ initRank(); }else if(msg.what==3){ initPersonRank(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.custom_info); init(); setAdapter(); } private void setAdapter() { // TODO Auto-generated method stub viewpager.setAdapter(new PagerAdapter() { @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub super.destroyItem(container, position, object); ((ViewPager) container).removeView(viewList.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub ((ViewPager) container).addView(viewList.get(position)); return viewList.get(position); } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0==arg1; } @Override public int getCount() { // TODO Auto-generated method stub return viewList.size(); } }); } private void init() { // TODO Auto-generated method stub viewpager = (ViewPager) findViewById(R.id.viewpager); LayoutInflater LI = LayoutInflater.from(CustomRecord.this); record = LI.inflate(R.layout.custom_record, null); rank = LI.inflate(R.layout.custom_rank, null); recordList = (ListView) record.findViewById(R.id.customList); final String str = Constant.CustomName; BmobQuery<PlayerData> players = new BmobQuery<PlayerData>(); players.addWhereEqualTo("name", str); players.order("-createdAt"); players.findObjects(CustomRecord.this, new FindListener<PlayerData>() { @Override public void onSuccess(List<PlayerData> playerDatas) { cRecords = (ArrayList<PlayerData>) playerDatas; Message message = new Message(); message.what =1; handle.sendMessage(message); } @Override public void onError(int arg0, String arg1) { // TODO Auto-generated method stub Toast.makeText(CustomRecord.this, "数据获取失败", Toast.LENGTH_SHORT).show(); } }); BmobQuery<PlayerData> players2 = new BmobQuery<PlayerData>(); players2.addWhereEqualTo("name", str); players2.order("-score,-createdAt"); players2.setLimit(1); players2.findObjects(CustomRecord.this, new FindListener<PlayerData>() { @Override public void onSuccess(List<PlayerData> arg0) { final Integer PMaxScore = arg0.get(0).getScore(); final String PMaxTime = arg0.get(0).getCreatedAt(); cRecordRank=new CRecord(); cRecordRank.setCname(str); cRecordRank.setCscore(PMaxScore); cRecordRank.setDateTime(PMaxTime); BmobQuery<PlayerData> players3 = new BmobQuery<PlayerData>(); players3.addWhereGreaterThanOrEqualTo("score", PMaxScore); players3.count(getApplicationContext(), PlayerData.class, new CountListener() { @Override public void onFailure(int arg0, String arg1) { // TODO Auto-generated method stub Toast.makeText(CustomRecord.this, "players3数据获取失败", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(int count) { // TODO Auto-generated method stub cRecordRank.setRank(count); Message message = new Message(); message.what =3; handle.sendMessage(message); } }); } @Override public void onError(int arg0, String arg1) { Toast.makeText(CustomRecord.this, "数据获取失败1", Toast.LENGTH_SHORT).show(); } }); BmobQuery<PlayerData> playersRank = new BmobQuery<PlayerData>(); playersRank.order("-score,createdAt"); playersRank.setLimit(3); playersRank.findObjects(getApplicationContext(), new FindListener<PlayerData>() { @Override public void onSuccess(List<PlayerData> arg0) { // TODO Auto-generated method stub cthreeRecords = (ArrayList<PlayerData>) arg0; Message message = new Message(); message.what =2; handle.sendMessage(message); } @Override public void onError(int arg0, String arg1) { // TODO Auto-generated method stub Toast.makeText(CustomRecord.this, "数据获取失败2", Toast.LENGTH_SHORT).show(); } }); viewList =new ArrayList<View>(); viewList.add(rank); viewList.add(record); cancel = (Button) rank.findViewById(R.id.cancel); logout = (Button) rank.findViewById(R.id.logout); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); logout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(CustomRecord.this,CustomLoginPage.class); startActivity(intent); finish(); } }); } class RecordList extends BaseAdapter{ @Override public int getCount() { // TODO Auto-generated method stub return cRecords.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return cRecords.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHandle viewHandle; if(convertView==null){ LayoutInflater inflate = LayoutInflater.from(CustomRecord.this); convertView = inflate.inflate(R.layout.record_part, null); viewHandle =new ViewHandle(); viewHandle.time = (TextView) convertView.findViewById(R.id.rtime); viewHandle.score = (TextView) convertView.findViewById(R.id.rscore); convertView.setTag(viewHandle); }else{ viewHandle=(ViewHandle) convertView.getTag(); } viewHandle.time.setText(cRecords.get(position).getCreatedAt().toString()); viewHandle.score.setText(cRecords.get(position).getScore().toString()); return convertView; } } class ViewHandle{ public TextView time; public TextView score; } private void initRank() { // TODO Auto-generated method stub num1Name = (TextView) rank.findViewById(R.id.num1name); num1Rank = (TextView) rank.findViewById(R.id.num1rank); num1Score = (TextView) rank.findViewById(R.id.num1score); num2Name = (TextView) rank.findViewById(R.id.num2name); num2Rank = (TextView) rank.findViewById(R.id.num2rank); num2Score = (TextView) rank.findViewById(R.id.num2score); num3Name = (TextView) rank.findViewById(R.id.num3name); num3Rank = (TextView) rank.findViewById(R.id.num3rank); num3Score = (TextView) rank.findViewById(R.id.num3score); num1Name.setText(cthreeRecords.get(0).getName()); num1Rank.setText(1+""); num1Score.setText(cthreeRecords.get(0).getScore().toString()); num2Name.setText(cthreeRecords.get(1).getName()); num2Rank.setText(2+""); num2Score.setText(cthreeRecords.get(1).getScore().toString()); num3Name.setText(cthreeRecords.get(2).getName()); num3Rank.setText(3+""); num3Score.setText(cthreeRecords.get(2).getScore().toString()); } public void initPersonRank(){ userName = (TextView) rank.findViewById(R.id.username); userRank = (TextView) rank.findViewById(R.id.userrank); userScore = (TextView) rank.findViewById(R.id.userscore); userName.setText(cRecordRank.getCname().toString()); userScore.setText(cRecordRank.getCscore().toString()); userRank.setText(cRecordRank.getRank()+""); } } ![图片说明](https://img-ask.csdn.net/upload/201810/19/1539953679_665565.png)
相见恨晚的超实用网站
搞学习 知乎:www.zhihu.com 简答题:http://www.jiandati.com/ 网易公开课:https://open.163.com/ted/ 网易云课堂:https://study.163.com/ 中国大学MOOC:www.icourse163.org 网易云课堂:study.163.com 哔哩哔哩弹幕网:www.bilibili.com 我要自学网:www.51zxw
花了20分钟,给女朋友们写了一个web版群聊程序
参考博客 [1]https://www.byteslounge.com/tutorials/java-ee-html5-websocket-example
爬虫福利二 之 妹子图网MM批量下载
爬虫福利一:27报网MM批量下载    点击 看了本文,相信大家对爬虫一定会产生强烈的兴趣,激励自己去学习爬虫,在这里提前祝:大家学有所成! 目标网站:妹子图网 环境:Python3.x 相关第三方模块:requests、beautifulsoup4 Re:各位在测试时只需要将代码里的变量 path 指定为你当前系统要保存的路径,使用 python xxx.py 或IDE运行即可。
字节跳动视频编解码面经
引言 本文主要是记录一下面试字节跳动的经历。 三四月份投了字节跳动的实习(图形图像岗位),然后hr打电话过来问了一下会不会opengl,c++,shador,当时只会一点c++,其他两个都不会,也就直接被拒了。 七月初内推了字节跳动的提前批,因为内推没有具体的岗位,hr又打电话问要不要考虑一下图形图像岗,我说实习投过这个岗位不合适,不会opengl和shador,然后hr就说秋招更看重基础。我当时
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
Python 基础(一):入门必备知识
目录1 标识符2 关键字3 引号4 编码5 输入输出6 缩进7 多行8 注释9 数据类型10 运算符10.1 常用运算符10.2 运算符优先级 1 标识符 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供
这30个CSS选择器,你必须熟记(上)
关注前端达人,与你共同进步CSS的魅力就是让我们前端工程师像设计师一样进行网页的设计,我们能轻而易举的改变颜色、布局、制作出漂亮的影音效果等等,我们只需要改几行代码,不需...
国产开源API网关项目进入Apache孵化器:APISIX
点击蓝色“程序猿DD”关注我回复“资源”获取独家整理的学习资料!近日,又有一个开源项目加入了这个Java开源界大名鼎鼎的Apache基金会,开始进行孵化器。项目名称:AP...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
编写Spring MVC控制器的14个技巧
本期目录 1.使用@Controller构造型 2.实现控制器接口 3.扩展AbstractController类 4.为处理程序方法指定URL映射 5.为处理程序方法指定HTTP请求方法 6.将请求参数映射到处理程序方法 7.返回模型和视图 8.将对象放入模型 9.处理程序方法中的重定向 10.处理表格提交和表格验证 11.处理文件上传 12.在控制器中自动装配业务类 ...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
求小姐姐抠图竟遭白眼?痛定思痛,我决定用 Python 自力更生!
点击蓝色“Python空间”关注我丫加个“星标”,每天一起快乐的学习大家好,我是 Rocky0429,一个刚恰完午饭,正在用刷网页浪费生命的蒟蒻...一堆堆无聊八卦信息的网页内容慢慢使我的双眼模糊,一个哈欠打出了三斤老泪,就在此时我看到了一张图片:是谁!是谁把我女朋友的照片放出来的!awsl!太好看了叭...等等,那个背景上的一堆鬼画符是什么鬼?!真是看不下去!叔叔婶婶能忍,隔壁老王的三姨妈的四表...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
相关热词 c#选择结构应用基本算法 c# 收到udp包后回包 c#oracle 头文件 c# 序列化对象 自定义 c# tcp 心跳 c# ice连接服务端 c# md5 解密 c# 文字导航控件 c#注册dll文件 c#安装.net
立即提问