用于选项卡的viewpager中的片段 - 在设置图像位图后图像不会重新绘制,并且所有选项卡都变为空白

时间:2014-04-24 10:58:58

标签: android android-fragments android-viewpager android-imageview android-tabs

我最近开始为Android设备编程 我正在使用 ViewPager 碎片(注意:我使用的是v4和v7支持库)
ActionBar (对于标签导航)。

Everythings运行正常,除非我尝试从URL获取到ImageView。
让我解释一下我的所作所为 -
1)我从我的服务器请求一张照片网址 2)我用它来设置imageview位图

Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
curlikeimage.setImageBitmap(bmp);


设置图像后,视图不会更新(I.E图像视图仍然是旧图像,没有来自URL的图像)

但是在我切换到另一个标签并返回带有imageview的标签后,图像视图图像会更新!
我尝试使用invalidate()和postinvalidate()但没有成功
发生的另一个奇怪的事情是,当我设置图像时(就像之前说过的,使用URL) 然后滑动到第3或第4个选项卡(我有4个选项卡 - tab1 | tab2 | tab3 | tab4,imageview在tab1上)
所有标签都变成空白(I.E它们消失了)

代码 -

MainActivity.java

      public class MainActivity extends android.support.v7.app.ActionBarActivity implements
android.support.v7.app.ActionBar.TabListener
{
    private ViewPager viewPager;
    private vertCollectionPagerAdapter mAdapter;
    private ActionBar actionBar;
    private String[] tabs = { "tab1", "tab2", "tab3","tab4" };
    public void setActionBar()
    {
viewPager = (ViewPager) findViewById(R.id.pager);

        actionBar = getSupportActionBar();
        FragmentManager fm = getSupportFragmentManager();
        mAdapter = new vertCollectionPagerAdapter(fm);
        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        actionBar.setTitle(Html.fromHtml("<font color=\"black\">AppTitle</font>"));
        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }


        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setActionBar();
    }
    public void SignOut()
    {
        LoginActivity.mApp.resetAccessToken();
        Intent i = new Intent(this,LoginActivity.class);
        finish();
        startActivity(i);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.action_signout:
            SignOut();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabReselected(Tab arg0,
            android.support.v4.app.FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab arg0,
            android.support.v4.app.FragmentTransaction arg1) {
        // TODO Auto-generated method stub
        viewPager.setCurrentItem(arg0.getPosition());

    }

    @Override
    public void onTabUnselected(Tab arg0,
            android.support.v4.app.FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }


}

vertCollectionPagerAdapter.java

public class vertCollectionPagerAdapter extends FragmentPagerAdapter {

    private static final int FRAGMENT_COUNT = 4;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
        // Google's Android MAP API 2 has MapFragment and the Android Support library's equivalent, SupportMapFragment
    private FragmentManager mFM;

    public boolean disableSwipe = false; 

    public vertCollectionPagerAdapter(FragmentManager fm) {
        super(fm);

        mFM = fm;

        // add fragments
        mFragments.add(new tab1frag());
        mFragments.add(new tab2frag());
        mFragments.add(new tab3frag());
        mFragments.add(new tab4frag());


    }

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

        // This is called by the ViewPager to get the fragment at tab position pos
        // ViewPager calls this when the Tab handler handles a tab change
    @Override
    public Fragment getItem(int pos) {
        Fragment f = mFragments.get(pos);
                // we want to disable swiping on the map fragment
            disableSwipe = false;

        return f;
    }

    public Fragment getActiveFragment(ViewPager container, int pos) {
        String name = "android:switcher:" + container.getId() + ":" + pos;

        return  mFM.findFragmentByTag(name);
    }

}

tab1frag.java

 public class tab1frag extends Fragment {
    public static String curPic = "";
    public View rootView;

    public ImageView curlikeimage;

    public void getNewPic() {
        curPic = "";

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {

                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://myserver/getimage");

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);
                    String result = EntityUtils.toString(response.getEntity());
                    Log.e("hey", result);
                    if (result.startsWith("OK")) {
                        response = null;
                        try {
                            HttpClient client = new DefaultHttpClient();
                            HttpGet request = new HttpGet();
                            String pic2get = result.substring(2);

                            request.setURI(new URI(
                                pic2get));
                            response = client.execute(request);
                            result = EntityUtils.toString(response.getEntity());
                            JSONObject json = new JSONObject(result);
                            Log.e("hey",
                                    json.getJSONObject("data")
                                            .getJSONObject("images")
                                            .getJSONObject(
                                                    "standard_resolution")
                                            .getString("url"));
                            URL url = new URL(json.getJSONObject("data")
                                    .getJSONObject("images")
                                    .getJSONObject("standard_resolution")
                                    .getString("url"));
                            Bitmap bmp = BitmapFactory.decodeStream(url
                                    .openConnection().getInputStream());
                            curlikeimage.setImageBitmap(bmp);
                            curlikeimage.postInvalidate();

                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {

                }

            }
        };
        thread.start();
    }

    private OnClickListener buttonClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            getNewPic();
        }
    };




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.tab1frag, container, false);
        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener(buttonClickListener);

        curlikeimage = (ImageView) rootView.findViewById(R.id.imageView1);
        return rootView;
    }
}

注意 GetPic方法中的pic2get变量是从服务器返回的JSONObject,它包含实际图像的URL 请注意,获取图像并在imageview中设置它不是(我认为)问题,因为我可以确认它确实设置了它
我过去一天试着寻找很多解决方案,但我找不到另一种适合我的解决方案。

0 个答案:

没有答案