如何在其他类中显示listview?

时间:2013-04-01 13:19:45

标签: android json listview arraylist android-lazyadapter

我制作了一个自定义动画滑动菜单(如fb),我必须在子布局中插入一个列表视图。但是listview是在一个不同的类中,使用lazyadapter通过json解析。

这是我的MainActivity

package com.android.appslu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.appslu.jsonparsing.JSONParsingActivity;


public class MainActivity extends Activity {



    private Button buttonSwitch;
private Button button1;
private View subLayout;
private View topLayout;
private ListView mylist;
private String ArrayList; // ={"Android","iPhone","BlackBerry","AndroidPeople"};
private Display display;
private View fakeLayout;
private AnimationListener AL;
// Values for after the animation
private int oldLeft;
private int oldTop;
private int newleft;
private int newTop;
private int screenWidth;
private int animToPostion;
// TODO change the name of the animToPostion for a better explanation.

private boolean menuOpen = false;

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


    buttonSwitch = (Button) findViewById(R.id.button);
    button1 = (Button) findViewById(R.id.button1);
    subLayout = findViewById(R.id.layout);
    topLayout = findViewById(R.id.layoutTwo);
    mylist = (ListView) findViewById(R.layout.list_item);
    fakeLayout = findViewById(R.id.fake_layouy);
    // TextView yourTextView = (TextView)findViewById(titleId);
    // yourTextView.setHighlightColor(R.color.red);



    // subViewListView.setAdapter((ListAdapter) new
    // ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,
    // ArrayList));
    // ListAdapter adapter = new SimpleAdapter(this,
    // mylist,R.layout.list_item, new String[]{TAG_NAME,TAG_URL}, new
    // int[]{R.id.name, R.id.url});

    display = getWindowManager().getDefaultDisplay();
    screenWidth = display.getWidth();
    int calcAnimationPosition = (screenWidth / 3);

    // Value where the onTop Layer has to animate
    // also the max width of the layout underneath
    // Set Layout params for subLayout according to calculation
    animToPostion = screenWidth - calcAnimationPosition;

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            animToPostion, LayoutParams.FILL_PARENT);
    subLayout.setLayoutParams(params);

    topLayout.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (menuOpen == true) {
                    animSlideLeft();
                }
            }

            return false;
        }
    });

    buttonSwitch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (menuOpen == false) {
                animSlideRight();

            } else if (menuOpen == true) {
                animSlideLeft();
            }
        }
    });


    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent newIntent = new Intent(MainActivity.this,   JSONParsingActivity.class);
            startActivity(newIntent);
        }
    });

    AL = new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {
            buttonSwitch.setClickable(false);
            topLayout.setEnabled(false);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            if (menuOpen == true) {
                Log.d("", "Open");
                topLayout.layout(oldLeft, oldTop,
                        oldLeft + topLayout.getMeasuredWidth(), oldTop
                                + topLayout.getMeasuredHeight());
                menuOpen = false;
                buttonSwitch.setClickable(true);
                topLayout.setEnabled(true);
            } else if (menuOpen == false) {
                Log.d("", "FALSE");
                topLayout.layout(newleft, newTop,
                        newleft + topLayout.getMeasuredWidth(), newTop
                                + topLayout.getMeasuredHeight());
                topLayout.setEnabled(true);
                menuOpen = true;
                buttonSwitch.setClickable(true);
            }
        }
    };
}

public void animSlideRight() {

    fakeLayout.setVisibility(View.VISIBLE);
    newleft = topLayout.getLeft() + animToPostion;
    newTop = topLayout.getTop();
    TranslateAnimation slideRight = new TranslateAnimation(0, newleft, 0, 0);
    slideRight.setDuration(500);
    slideRight.setFillEnabled(true);
    slideRight.setAnimationListener(AL);
    topLayout.startAnimation(slideRight);

}

public void animSlideLeft() {

    fakeLayout.setVisibility(View.GONE);
    oldLeft = topLayout.getLeft() - animToPostion;
    oldTop = topLayout.getTop();
    TranslateAnimation slideLeft = new TranslateAnimation(newleft, oldLeft,
            0, 0);
    slideLeft.setDuration(500);
    slideLeft.setFillEnabled(true);
    slideLeft.setAnimationListener(AL);
    topLayout.startAnimation(slideLeft);
}
}`

JSONParsingActivity是

package com.android.appslu.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.appslu.MainActivity;
import com.android.appslu.R;

public class JSONParsingActivity extends ListActivity {
private static String url = "http:EXAMPLE.COM";
// JSON Node names

private static final String TAG_CONTACTS = "Categories";
private static final String TAG_CATBOOK = "BuzzByappcategory";
private static final String TAG_APPS = "BuzzBysource";

static final String TAG_NAME = "CatName";
private static final String TAG_ID = "CatId";
static final String TAG_EMAIL = "CatIcon";
//private static final String TAG_PHONE_HOME = "home";

//  private static final String TAG_PHONE_OFFICE = "office";


    Bitmap image;
// contacts JSONArray
JSONObject catlist = null;
JSONArray catbook = null;
JSONArray catapps = null;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_item);

    // Hashmap for ListView

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

    // Creating JSON Parser instance
    Jparser jParser = new Jparser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONfromUrl(url);

    try {
        // Getting Array of Contacts
        catlist = json.getJSONObject(TAG_CONTACTS);

        catbook = catlist.getJSONArray(TAG_CATBOOK);
        // looping through All Contacts
        for(int i = 0; i < catbook.length(); i++){
            JSONObject c = catbook.getJSONObject(i);




            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
//          String address = c.getString(TAG_ADDRESS);
    //      String gender = c.getString(TAG_GENDER);

            // Phone number is agin JSON Object
//              JSONObject phone = c.getJSONObject(TAG_PHONE);
//              String mobile = phone.getString(TAG_PHONE_MOBILE);
//              String home = phone.getString(TAG_PHONE_HOME);
//              String office = phone.getString(TAG_PHONE_OFFICE);
//              
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);
            map.put(TAG_EMAIL, email);
    //      map.put(TAG_PHONE_MOBILE, mobile);

            // adding HashList to ArrayList
            catList.add(map);
        }

        catapps = catlist.getJSONArray(TAG_APPS);
        // looping through All Contacts
        for(int i = 0; i < catapps.length(); i++){
            JSONObject c = catapps.getJSONObject(i);




            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
//          String address = c.getString(TAG_ADDRESS);
    //      String gender = c.getString(TAG_GENDER);

            // Phone number is agin JSON dObject
//              JSONObject phone = c.getJSONObject(TAG_PHONE);
//              String mobile = phone.getString(TAG_PHONE_MOBILE);
//              String home = phone.getString(TAG_PHONE_HOME);
//              String office = phone.getString(TAG_PHONE_OFFICE);
//              
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);
            map.put(TAG_EMAIL, email);
    //      map.put(TAG_PHONE_MOBILE, mobile);

            // adding HashList to ArrayList
            catList.add(map);
        }

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

    }



    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new LazyAdapter(this, catList);
    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    // Launching new screen on Selecting Single ListItem
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String cost = ((ImageView) view.findViewById(R.id.email)).getTag().toString();
//              String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            //in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

//      Intent i=new Intent(JSONParsingActivity.this,MainActivity.class);
//         i.putStringArrayListExtra("key",arl);
//         startActivity(i);
//      

} 

}

主要活动的xml是

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<SurfaceView
    android:id="@+id/surfaceView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

<RelativeLayout
    android:id="@+id/layout"
    android:layout_width="220dp"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/fake_layouy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone" >
    </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView 
            android:id="@+id/name_label"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <ImageView android:id="@+id/email_label"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ListView>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/layoutTwo"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/scrollback"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="2dp"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/layoutThree"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_below="@+id/button" >
        </ListView>

        <Button
            android:id="@+id/button"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:text="slide" />

    </LinearLayout>
</RelativeLayout>

我的问题是如何在MainActivity的子布局中显示JSONParsingActivity的列表视图。

我是Android编程的新手...... Plz帮助..

提前致谢..

1 个答案:

答案 0 :(得分:1)

使用ListFragment扩展您的JSONParsingActivity。在主Activity中加载JSONParsingActivity

已更新为代码

FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

然后,您可以使用add()方法添加片段,指定要添加的片段以及要插入的视图。

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

refer this link,这里解释有关片段的所有内容。

这是在片段中设置UserInterface的方法。第一个解决方案1。

public static class ExampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.example_fragment, container, false);
}
}

解决第二个问题。

  LazyAdapter(getActivity(), ArrayList<HashMap<String,String>>)