使用viewpager进行水平分页

时间:2014-11-26 06:37:24

标签: android android-viewpager android-webview horizontal-scrolling

我需要在滑动时实现页面的水平滚动

我已经按照json的顺序加载了数据,在textview和webview

我使用了viewpager来实现该操作

我收到了log cat

中显示的错误

我使用了removeView()方法,错误再次出现

请帮我解决这个问题

提前致谢

我的代码

package singlearticle;


import com.yslabs.yourstory.R;


import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
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.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

@SuppressLint("SetJavaScriptEnabled")
public class SingleArticle extends Activity {

    String t = single.title;
    String p = single.permalink;
    String f = single.featured_img;
    String a = single.author;
    String d = single.date;
    String articleComment = "article url" + p;
    private WebView web1, fbCommentview;
    ConnectionDetector checkConnection;
    Boolean isInternetPresent = false;
    ViewPager viewPage;
    MyPagerAdapter mypageAdapter;
    private ProgressDialog pDialog;

    @SuppressWarnings("deprecation")
    @SuppressLint({ "InflateParams", "SetJavaScriptEnabled", "HandlerLeak",
            "NewApi" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.singlearticle);
        viewPage = (ViewPager) findViewById(R.id.myviewpager);
        mypageAdapter = new MyPagerAdapter();
        viewPage.setAdapter(mypageAdapter);
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#f8f8f8")));
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        ActionBar mActionBar = getActionBar();
        mActionBar.setDisplayShowHomeEnabled(true);
        mActionBar.setDisplayShowTitleEnabled(false);


        LayoutInflater mInflater = LayoutInflater.from(SingleArticle.this);
        View mCustomView = mInflater
                .inflate(R.layout.customactionbar,null);
        TextView mTitleTextView = (TextView) mCustomView
                .findViewById(R.id.title_text);
        Typeface fontt = Typeface.createFromAsset(getAssets(),
                "helvetica.ttf");
        mTitleTextView.setTypeface(fontt);
        mActionBar.setCustomView(mCustomView);
        mActionBar.setDisplayShowCustomEnabled(true);
        mActionBar.setLogo(R.drawable.backicon);
        // getActionBar().setIcon(
        // new
        // ColorDrawable(getResources().getColor(android.R.color.transparent)));
        pDialog = new ProgressDialog(SingleArticle.this);
        pDialog.setMessage("Loading...");
        pDialog.show();
        pDialog.setCancelable(false);
        final Handler h = new Handler() {
            public void handleMessage(Message message) {
                pDialog.dismiss();
            }
        };
        h.sendMessageDelayed(new Message(), 500);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main2, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_refresh:
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, t + "\n" + p);
            sendIntent.setType("text/plain");
            startActivity(sendIntent);

            return true;
        case android.R.id.home:
            onBackPressed();
            web1.loadUrl("");
            web1.stopLoading();
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public class myWebClient extends WebViewClient

    {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            // TODO Auto-generated method stub

            super.onPageStarted(view, url, favicon);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            // TODO Auto-generated method stub

            view.loadUrl(url);

            return true;

        }

        @Override
        public void onPageFinished(WebView view, String url) {

            // TODO Auto-generated method stub

            super.onPageFinished(view, url);

            // progressBar.setVisibility(View.GONE);

        }

    }

    // To handle "Back" key press event for WebView to go back to previous
    // screen.

    @SuppressWarnings("static-access")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)

    {

        if (keyCode == event.KEYCODE_BACK) {
            web1.loadUrl("");
            web1.stopLoading();

            finish();

        }
        return super.onKeyDown(keyCode, event);

    }

    private class MyPagerAdapter extends PagerAdapter {

        int articleCount = 5;

        @Override
        public int getCount() {
            // returns article count
            return articleCount;
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            // assigns object to view

            return view == ((LinearLayout)obj);
        }

        @SuppressLint("NewApi")
        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            d = d.substring(0, d.length() - 3);

            String c = single.content;
            c = c.replace("src=\"//", "src=\"https://");
            final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
            String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
            String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
                    + c + "</body></html>";
            TextView titleTxt = (TextView) findViewById(R.id.singletitle);
            titleTxt.setText(t);
            // tt = titleTxt.getText().toString();
            Typeface font = Typeface.createFromAsset(getAssets(),
                    "Helvetica Neue UltraLight.ttf");
            Typeface font22 = Typeface.createFromAsset(getAssets(),
                    "helvetica-neue-regular-1361522098.ttf");
            titleTxt.setTypeface(font);
            titleTxt.setTypeface(font22);
            titleTxt.setTypeface(null, Typeface.BOLD);
            TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
            authorTxt.setText(a);
            Typeface font1 = Typeface.createFromAsset(getAssets(),
                    "helvetica.ttf");
            authorTxt.setTypeface(font1);
            TextView dateTxt = (TextView) findViewById(R.id.singledate);
            dateTxt.setText(d);
            Typeface font2 = Typeface.createFromAsset(getAssets(),
                    "helvetica.ttf");
            dateTxt.setTypeface(font2);
            TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
            permalinkTxt.setText(p);
            permalinkTxt.setVisibility(View.GONE);
            // pp = permalinkTxt.getText().toString();
            // datep.setVisibility(View.GONE);

            web1 = (WebView) findViewById(R.id.webView2);
            web1.setWebViewClient(new myWebClient());
            web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            web1.getSettings().setJavaScriptEnabled(true);
            // web1.getSettings().setJavaScriptEnabled(true);
            // web1.setInitialScale(65);
            web1.getSettings().setDefaultFontSize(18);
            web1.setWebChromeClient(new WebChromeClient());
            web1.getSettings().setPluginState(PluginState.ON_DEMAND);
            // web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
            web1.loadData(htmldata, "text/html; charset=utf-8", null);

            web1.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    Intent in = new Intent(SingleArticle.this, webview.class);
                    webclass.webdata = url.toString();
                    startActivity(in);
                    return true;
                }

            });

            fbCommentview = (WebView) findViewById(R.id.fbCommentview);
            /*
             * to check internet and show/hide facebook part
             */
            checkConnection = new ConnectionDetector(getApplicationContext());
            isInternetPresent = checkConnection.isConnectingToInternet();
            if (isInternetPresent) {
                // Toast.makeText(getApplicationContext(),"Internet Working",
                // Toast.LENGTH_SHORT).show();
                fbCommentview.setVisibility(View.VISIBLE);
            } else {
                // Toast.makeText(getApplicationContext(),"Internet Not Working",
                // Toast.LENGTH_SHORT).show();
                fbCommentview.setVisibility(View.GONE);
            }
            fbCommentview.setWebViewClient(new myWebClient());
            fbCommentview.getSettings()
                    .setJavaScriptCanOpenWindowsAutomatically(true);
            fbCommentview.getSettings().setJavaScriptEnabled(true);
            fbCommentview.getSettings().setDefaultFontSize(18);
            fbCommentview.setWebChromeClient(new WebChromeClient());
            fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
            fbCommentview.loadUrl(articleComment);

            System.out.println("Title" + t);
            System.out.println("Content" +c);
            LinearLayout layout = new LinearLayout(SingleArticle.this);
            layout.setOrientation(LinearLayout.VERTICAL);
            LayoutParams layoutParams = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            layout.setLayoutParams(layoutParams);
            layout.addView(titleTxt);
            layout.addView(dateTxt);
            layout.addView(web1);
            layout.addView(fbCommentview);
            container.addView(layout);
            return layout;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((LinearLayout) object);
        }

    }

}

LOGCAT中的错误 error in logcat

2 个答案:

答案 0 :(得分:0)

这里

TextView titleTxt = (TextView) findViewById(R.id.singletitle);
TextView authorTxt = (TextView) findViewById(R.id.singleauthor);
TextView permalinkTxt = (TextView) findViewById(R.id.singleperlink);
web1 = (WebView) findViewById(R.id.webView2);
fbCommentview = (WebView) findViewById(R.id.fbCommentview);

这些所有视图都包含一个父级..因为这个原因你无法再添加它..如果你想在这里添加到布局。你必须像这样创建那些textview,而不是从xml中获取。

TextView textView = new TextView(MainActivity.this);

然后添加到布局。

答案 1 :(得分:0)

替换以下方法并尝试:

    @Override
        public Object instantiateItem(ViewGroup container, int position) {

            LayoutInflater inflater;
            View view = inflater.inflate(R.layout.singlearticle, container, false);
            d = d.substring(0, d.length() - 3);

            String c = single.content;
            c = c.replace("src=\"//", "src=\"https://");
            final String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
            String urlEncoded = Uri.encode(c, ALLOWED_URI_CHARS);
            String htmldata = "<!DOCTYPE html><html><style = text/css> img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a { color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
                    + c + "</body></html>";
            TextView titleTxt = (TextView)view.findViewById(R.id.singletitle);
            titleTxt.setText(t);
            // tt = titleTxt.getText().toString();
            Typeface font = Typeface.createFromAsset(getAssets(),
                    "Helvetica Neue UltraLight.ttf");
            Typeface font22 = Typeface.createFromAsset(getAssets(),
                    "helvetica-neue-regular-1361522098.ttf");
            titleTxt.setTypeface(font);
            titleTxt.setTypeface(font22);
            titleTxt.setTypeface(null, Typeface.BOLD);
            TextView authorTxt = (TextView)view.findViewById(R.id.singleauthor);
            authorTxt.setText(a);
            Typeface font1 = Typeface.createFromAsset(getAssets(),
                    "helvetica.ttf");
            authorTxt.setTypeface(font1);
            TextView dateTxt = (TextView)view.findViewById(R.id.singledate);
            dateTxt.setText(d);
            Typeface font2 = Typeface.createFromAsset(getAssets(),
                    "helvetica.ttf");
            dateTxt.setTypeface(font2);
            TextView permalinkTxt = (TextView)view.findViewById(R.id.singleperlink);
            permalinkTxt.setText(p);
            permalinkTxt.setVisibility(View.GONE);
            // pp = permalinkTxt.getText().toString();
            // datep.setVisibility(View.GONE);

            web1 = (WebView)view.findViewById(R.id.webView2);
            web1.setWebViewClient(new myWebClient());
            web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            web1.getSettings().setJavaScriptEnabled(true);
            // web1.getSettings().setJavaScriptEnabled(true);
            // web1.setInitialScale(65);
            web1.getSettings().setDefaultFontSize(18);
            web1.setWebChromeClient(new WebChromeClient());
            web1.getSettings().setPluginState(PluginState.ON_DEMAND);
            // web1.loadUrl("http://dev.skyle.co/fbSDK.php?data="+urlEncoded);
            web1.loadData(htmldata, "text/html; charset=utf-8", null);

            web1.setWebViewClient(new WebViewClient() {

                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    Intent in = new Intent(SingleArticle.this, webview.class);
                    webclass.webdata = url.toString();
                    startActivity(in);
                    return true;
                }

            });

            fbCommentview = (WebView)view.findViewById(R.id.fbCommentview);
            /*
             * to check internet and show/hide facebook part
             */
            checkConnection = new ConnectionDetector(getApplicationContext());
            isInternetPresent = checkConnection.isConnectingToInternet();
            if (isInternetPresent) {
                // Toast.makeText(getApplicationContext(),"Internet Working",
                // Toast.LENGTH_SHORT).show();
                fbCommentview.setVisibility(View.VISIBLE);
            } else {
                // Toast.makeText(getApplicationContext(),"Internet Not Working",
                // Toast.LENGTH_SHORT).show();
                fbCommentview.setVisibility(View.GONE);
            }
            fbCommentview.setWebViewClient(new myWebClient());
            fbCommentview.getSettings()
                    .setJavaScriptCanOpenWindowsAutomatically(true);
            fbCommentview.getSettings().setJavaScriptEnabled(true);
            fbCommentview.getSettings().setDefaultFontSize(18);
            fbCommentview.setWebChromeClient(new WebChromeClient());
            fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
            fbCommentview.loadUrl(articleComment);

//            System.out.println("Title" + t);
//            System.out.println("Content" +c);
//            LinearLayout layout = new LinearLayout(SingleArticle.this);
//            layout.setOrientation(LinearLayout.VERTICAL);
//            LayoutParams layoutParams = new LayoutParams(
//                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//            layout.setLayoutParams(layoutParams);
//            layout.addView(titleTxt);
//            layout.addView(dateTxt);
//            layout.addView(web1);
//            layout.addView(fbCommentview);
//            container.addView(layout);
            return view;

        }