将活动类别更改为片段 [英] Change Activity Class to Fragment

查看:65
本文介绍了将活动类别更改为片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的Android开发者.我有一个扩展Activity的类,我想更改为Fragment.我知道它会使用onCreateView(LayoutInflater, ViewGroup, Bundle)作为一个片段,但是我不确定如何将我的工作活动更改为一个片段.

I'm pretty new new Android development. I have a class that extends Activity and I'd like to change to to a Fragment. I know as a fragment it would use onCreateView(LayoutInflater, ViewGroup, Bundle) but I'm not sure how to change my working activity to a fragment.

我已经开始工作了.现在的问题是,我的RSS feed中的列表没有显示.我得到了加载指示器,完成后它会停止,但列表不会显示.

I have gotten it kind of working. The problem now is that my list from the RSS feed isn't showing. I get my loading indicator and it stops once it's finished but the list doesn't show.

实际上列表正在显示,但是文本与背景颜色相同,所以我看不到它.

Actually the list is showing, but the text is the same color as the background so I couldn't see it.

这是我现有的活动:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ActionAlerts extends Activity {

    ListView listFeed;
    ProgressBar prgLoading;
    TextView txtAlert;

    ActionAlertsAdapter la;

    static String[] title;
    static String[] pubDate;
    static String[] link;

    String URLFeed;

    URL Feed;
    DocumentBuilder db;
    Document doc;
    NodeList nodeList;
    Bundle rssBundle = new Bundle();


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actionalerts);

        Bundle b = getIntent().getExtras();

        URLFeed = b.getString("url");



        la = new ActionAlertsAdapter(this);

        listFeed = (ListView) findViewById(R.id.listFeed);
        prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
        txtAlert = (TextView) findViewById(R.id.txtAlert);

        // ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
        ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
        listFeed.setDivider(blackColor);
        listFeed.setDividerHeight(3);


        new getDataTask().execute();


        listFeed.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub


                Intent web = new Intent(ActionAlerts.this, WebBrowser.class);
                rssBundle.putString("myURL", link[position]);
                web.putExtras(rssBundle);
                startActivity(web);

            }
        });
    }


    /** this class is used to handle thread */
    public class getDataTask extends AsyncTask<Void, Void, Void>{


        @Override
         protected void onPreExecute() {
          // TODO Auto-generated method stub

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            getDataFromFeed();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            //dialog.dismiss();
            prgLoading.setVisibility(8);
            if(title != null){
                listFeed.setVisibility(0);
                listFeed.setAdapter(la);
            }else{
                txtAlert.setVisibility(0);
            }
        }
    }

    /*
     * This code is used to get data from feed and store them
     * to array attributes
     */
    public void getDataFromFeed(){

        try {
            Feed = new URL(URLFeed);
            DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
            doc = db.parse(new InputSource(Feed.openStream()));
            doc.getDocumentElement().normalize();
            nodeList = doc.getElementsByTagName("item");

            title = new String[nodeList.getLength()];
            pubDate = new String[nodeList.getLength()];
            link = new String[nodeList.getLength()];

            for(int i=0;i<nodeList.getLength();i++){
                Node node = nodeList.item(i);

                Element fstElmnt = (Element) node;

                NodeList titleList = fstElmnt.getElementsByTagName("title");
                Element titleElement = (Element) titleList.item(0);
                titleList = titleElement.getChildNodes();
                title[i] = ((Node) titleList.item(0)).getNodeValue();

                NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
                Element pubDateElement = (Element) pubDateList.item(0);
                pubDateList = pubDateElement.getChildNodes();
                pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
                // chops off the " +0000" on date
                pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);

                NodeList linkList = fstElmnt.getElementsByTagName("link");
                Element linkElement = (Element) linkList.item(0);
                linkList = linkElement.getChildNodes();
                link[i] = ((Node) linkList.item(0)).getNodeValue();
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig)
    {
        // Ignore orientation change to keep activity from restarting
        super.onConfigurationChanged(newConfig);
    }
}

这是我的适配器类:

package kyfb.android.kyfb.com.kyfb;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

class ActionAlertsAdapter extends BaseAdapter {
    private LayoutInflater inflater;

    public ActionAlertsAdapter(Context context) {

        inflater = LayoutInflater.from(context);
    }

    public int getCount() {
        // TODO Auto-generated method stub

        return ActionAlertsFragment.title.length;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;

        if(convertView == null){
            convertView = inflater.inflate(R.layout.item_feed, null);
            holder = new ViewHolder();
            holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
            holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
            holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        if((position%2)!=0){
            // holder.lytItemFeed.setBackgroundResource(R.drawable.row_1);
            holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
        }else{
            // holder.lytItemFeed.setBackgroundResource(R.drawable.row_2);
            holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
        }

        holder.txtTitle.setText(ActionAlertsFragment.title[position]);
        holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);

        holder.txtTitle.setTextColor(Color.BLACK);
        holder.txtPubDate.setTextColor(Color.BLACK);

        return convertView;
    }

    static class ViewHolder {
        TextView txtTitle, txtPubDate;
        RelativeLayout lytItemFeed;
    }
}

这是我要从上面的活动类制作的Fragment类:

Here is my Fragment class that I'm trying to make from the activity class above:

   package kyfb.android.kyfb.com.kyfb;

import android.app.Fragment;
import android.app.ListFragment;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class ActionAlertsFragment extends Fragment {

    ListView listFeed;
    ProgressBar prgLoading;
    TextView txtAlert;

    ActionAlertsAdapter la;

    static String[] title;
    static String[] pubDate;
    static String[] link;

    String URLFeed;

    URL Feed;
    DocumentBuilder db;
    Document doc;
    NodeList nodeList;
    Bundle rssBundle = new Bundle();

    public ActionAlertsFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        // View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);
        View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);

        URLFeed = "http://kyfbnewsroom.com/category/notifications/feed";

        Context ctx = rootView.getContext();

        la = new ActionAlertsAdapter(ctx);

        listFeed = (ListView) rootView.findViewById(R.id.listFeed);
        prgLoading = (ProgressBar) rootView.findViewById(R.id.prgLoading);
        txtAlert = (TextView) rootView.findViewById(R.id.txtAlert);

        // ColorDrawable whiteColor = new ColorDrawable(Color.WHITE);
        ColorDrawable blackColor = new ColorDrawable(Color.BLACK);
        listFeed.setDivider(blackColor);
        listFeed.setDividerHeight(3);

        new getDataTask().execute();

        listFeed.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub

                // Intent web = new Intent(ActionAlertsFragment.this, WebBrowser.class);
                // rssBundle.putString("myURL", link[position]);
                // web.putExtras(rssBundle);
                // startActivity(web);
            }
        });

        return rootView;
    }

    /** this class is used to handle thread */
    public class getDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            getDataFromFeed();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            //dialog.dismiss();
            prgLoading.setVisibility(8);
            if(title != null){
                listFeed.setVisibility(0);
                listFeed.setAdapter(la);
            }else{
                txtAlert.setVisibility(0);
            }
        }
    }

    /*
     * This code is used to get data from feed and store them
     * to array attributes
     */
    public void getDataFromFeed(){

        try {
            Feed = new URL(URLFeed);
            DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
            doc = db.parse(new InputSource(Feed.openStream()));
            doc.getDocumentElement().normalize();
            nodeList = doc.getElementsByTagName("item");

            title = new String[nodeList.getLength()];
            pubDate = new String[nodeList.getLength()];
            link = new String[nodeList.getLength()];

            for(int i=0;i<nodeList.getLength();i++){
                Node node = nodeList.item(i);

                Element fstElmnt = (Element) node;

                NodeList titleList = fstElmnt.getElementsByTagName("title");
                Element titleElement = (Element) titleList.item(0);
                titleList = titleElement.getChildNodes();
                title[i] = ((Node) titleList.item(0)).getNodeValue();

                NodeList pubDateList = fstElmnt.getElementsByTagName("pubDate");
                Element pubDateElement = (Element) pubDateList.item(0);
                pubDateList = pubDateElement.getChildNodes();
                pubDate[i] = ((Node) pubDateList.item(0)).getNodeValue();
                // chops off the " +0000" on date
                pubDate[i] = pubDate[i].substring(0, pubDate[i].length()-14);

                NodeList linkList = fstElmnt.getElementsByTagName("link");
                Element linkElement = (Element) linkList.item(0);
                linkList = linkElement.getChildNodes();
                link[i] = ((Node) linkList.item(0)).getNodeValue();
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig)
    {
        // Ignore orientation change to keep activity from restarting
        super.onConfigurationChanged(newConfig);
    }
}

推荐答案

首先更改此内容.

View rootView = inflater.inflate(R.layout.fragment_actionalerts, null);

View rootView = inflater.inflate(R.layout.fragment_actionalerts, container, false);

并使用Fragment Context作为getActivity().

这篇关于将活动类别更改为片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆