如何将ListActivity类提取到SherlockFragment中

时间:2013-08-03 10:32:20

标签: android listview listactivity fragment-tab-host

我是Android和Java的新手。我按照AndroidBegin's教程使用SherlockFragment创建了3个标签。我想要做的是当我点击时将通知流式传输到第一个标签。流通知的显示是ListView。我创建了一个名为StreamNotices.java的类,它运行良好。我的问题是,当我按下“标签1”时,如何获取/调用此类并加载我的内容?

ETA:如果你能特意告诉我把它放在哪里会很好,因为我对我应该放置代码的位置一无所知。

帮助会很棒!!

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {
// Declare Variables    
private FragmentTabHost mTabHost;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the view from main_fragment.xml
    setContentView(R.layout.main_fragment);

    // Locate android.R.id.tabhost in main_fragment.xml
    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

    // Create the tabs in main_fragment.xml
    mTabHost.setup(this, getSupportFragmentManager(), R.id.tabcontent);

    // Create Tab1 with a custom image in res folder
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
            FragmentTab1.class, null);

    // Create Tab2
    mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
            FragmentTab2.class, null);

    // Create Tab3
    mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"),
            FragmentTab3.class, null);
}

}

FragmentTab1.java

public class FragmentTab1 extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
    return rootView;
}

}

StreamNotices.java(来自mybringback.com的示例代码)

public class StreamNotices extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

.....

// JSON IDS:
private static final String TAG_NOTICE = "notice";
private static final String TAG_ANNOUNCEMENTID = "announcementid";
private static final String TAG_DEPTNO = "deptno";
private static final String TAG_MODULEID = "moduleid";
private static final String TAG_SUBJECT = "subject"; 
private static final String TAG_MESSAGE = "message";
private static final String TAG_SUCCESS = "success";
// it's important to note that the message is both in the parent branch of
// our JSON tree that displays a "Post Available" or a "No Post Available"
// message,
// and there is also a message for each individual post, listed under the
// "posts"
// category, that displays what the user typed as their message.

// An array of all of our comments
private JSONArray mComments = null;

// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // note that use read_comments.xml instead of our single_post.xml
    setContentView(R.layout.announcements);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}


/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content, for example,
    // message it the tag, and "I'm awesome" as the content..

    mCommentList = new ArrayList<HashMap<String, String>>();

    // Bro, it's time to power up the J parser
    JSONParser jParser = new JSONParser();
    // Feed the beast our comments url, and it spits us
    // back a JSON object. Boo-yeah Jerome.
    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

    // when parsing JSON stuff, we should probably
    // try to catch any exceptions:
    try {

        // I know I said we would check if "Posts were Avail." (success==1)
        // before we tried to read the individual posts, but I lied...
        // mComments will tell us how many "posts" or comments are
        // available
        mComments = json.getJSONArray(TAG_NOTICE);

        // looping through all posts according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            // gets the content of each tag
        String id = c.getString(TAG_ANNOUNCEMENTID);
                    String name = c.getString(TAG_DEPTNO);
                    String module = c.getString(TAG_MODULEID);
                    String title = c.getString(TAG_SUBJECT);
                    String content = c.getString(TAG_MESSAGE);
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_ANNOUNCEMENTID, id);
                    map.put(TAG_DEPTNO, name);
                    map.put(TAG_MODULEID, module);
                    map.put(TAG_SUBJECT, title);
                    map.put(TAG_MESSAGE, content);

            // adding HashList to ArrayList
            mCommentList.add(map);

            // annndddd, our JSON data is up to date same with our array
            // list
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to do
    //that, we need to create a ListAdapter.  This SimpleAdapter,
    //will utilize our updated Hashmapped ArrayList, 
    //use our single_post xml template for each item in our list,
    //and place the appropriate info from the list to the
    //correct GUI id.  Order is important here.
    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[] { TAG_ANNOUNCEMENTID,
                            TAG_DEPTNO, TAG_MODULEID, TAG_SUBJECT, TAG_MESSAGE},
                    new int[] { R.id.announcementid, R.id.deptno, R.id.moduleid,
                    R.id.subject, R.id.message });

    // I shouldn't have to comment on this one:
    setListAdapter(adapter);

    // Optional: when the user clicks a list item we 
    //could do something.  However, we will choose
    //to do nothing...
    ListView lv = getListView();    
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // This method is triggered if an item is click within our
            // list. For our example we won't be using this, but
            // it is useful to know in real life applications.

        }
    });
}

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(StreamNotices.this);
        pDialog.setMessage("Loading Comments...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
}

}

我的XML文件:

announcements.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#fff" >
<TextView
        android:id="@+id/app_name_text"
        style="@style/BlackText"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="@string/read_notices_title"
        android:textAppearance="?android:attr/textAppearanceLarge" />

<ListView
    android:id="@android:id/list"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="#fff"
    android:divider="@android:color/transparent"
    android:dividerHeight="10dp"
    android:scrollbars="vertical"
    android:textColor="#000" >

</ListView></LinearLayout>

single_post.xml(通知会在流入公告之前流向此处)

enter code here<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/roundback"
android:paddingLeft="10dp"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:orientation="vertical" >

<!-- Announcement id layout -->
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">


            <TextView
                android:id="@+id/announcementid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:textColor="#333"
                android:textStyle="bold" 
                android:visibility="gone"/>
            </LinearLayout>

     <!-- date layout -->
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:gravity="right"
        android:textStyle="bold"
        android:text="@string/posted_date" >
        </TextView>

            <TextView
                android:id="@+id/posted_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:textColor="#333"
                android:textStyle="bold" />
            </LinearLayout>


          <!-- Dept ID -->
          <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

               <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#5d5d5d"
                android:gravity="left"
                android:textStyle="bold"
                android:text="@string/deptid" />

                <TextView
                    android:id="@+id/deptno"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:textColor="#acacac"
                    android:textStyle="bold" >
                </TextView>
             </LinearLayout>

          <!-- Module id -->


          <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
               <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#5d5d5d"
                android:gravity="left"
                android:textStyle="bold"
                android:text="@string/mid" />

                 <TextView
                    android:id="@+id/moduleid"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:textColor="#acacac"
                    android:textStyle="bold" >
                </TextView>
         </LinearLayout>

          <!-- subject -->
          <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                   <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="#5d5d5d"
                    android:gravity="left"
                    android:textStyle="bold"
                    android:text="@string/subj" />

                    <TextView
                    android:id="@+id/subject"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:textColor="#acacac"
                    android:textStyle="bold" >
                </TextView>
            </LinearLayout>    

        <!-- message -->
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">


            <TextView
                android:id="@+id/message"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="2dip"
                android:paddingLeft="8dp"
                android:textColor="#888" >
            </TextView>

            </LinearLayout>

     </LinearLayout>

1 个答案:

答案 0 :(得分:0)

单击onClick()中的

如果您使用android.support.v.4。文库

FragmentTransaction fTrans = getSupportFragmentManager().beginTransaction();
    fTrans.add(R.id.frame_layout_inActivity_class, new Fragment());
    fTrans.commit();

或者如果你不使用它

FragmentTransaction fTrans = getFragmentManager().beginTransaction();
    fTrans.add(R.id.frame_layout_inActivity_class, new Fragment());
    fTrans.commit();