0

您好,我已经构建了智能手机应用程序,但现在我开始着手一个项目,以使我的应用程序与平板电脑兼容。现在我正在使用片段,这是我第一次使用片段,所以这就是为什么我需要你的建议,请帮助或用我的代码给我示例。非常感谢

我的代码我的“新闻”类:

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

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

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class Nieuws extends FragmentActivity{

    // Connection detector
    //ConnectionDetector cd;

    // Alert dialog manager
    //AlertDialogManager alert = new AlertDialogManager();

    // Progress Dialog
    //private ProgressDialog pDialog;

    private static String URL = "http://localhost/fetch.php?page=2&android";

    // JSON Node namen
    static final String TAG_DATA = "data";
    static final String TAG_ID = "id";
    static final String TAG_CATEGORY = "category";
    static final String TAG_TITLE = "title";
    static final String TAG_AUTHOR = "author";
    static final String TAG_DATE = "date";
    static final String TAG_INTRODUCTION = "introduction";
    static final String TAG_CONTENT = "content";
    static final String TAG_THUMBNAIL = "thumbnail";
    static final String TAG_MEDIA = "media";
    static final String TAG_SOURCE = "source";
    static final String TAG_LINKEDMEDIA = "linkedMedia"; //array waarin de plaatjes zitten*/

    // Nieuws JSONArray
    JSONArray newsArray;

    ListView list;
    LazyAdapter adapter;

    private PullToRefreshListView mPullRefreshListView;

    ArrayList<HashMap<String, String>> newsList; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nieuws);
    //list=(ListView)findViewById(R.id.list);
    mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_to_refresh_listview);

/*    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    StartFragment myFragment = new StartFragment();
    ft.add(R.id.myFragment, myFragment);
    ft.commit();*/

    /*  cd = new ConnectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(Nieuws.this, "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
        // stop executing code by return
        return;
    }*/

    // Set a listener to be invoked when the list should be refreshed.
    mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
        @Override
        public void onRefresh(PullToRefreshBase<ListView> refreshView) {

            // Do work to refresh the list here.
            new GetJSONData().execute();
        }
    });

    //Async 
    new GetJSONData().execute();

}


class GetJSONData extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>{

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        //pDialog = new ProgressDialog(Nieuws.this);
        //pDialog.setMessage("Nieuws laden ...");
        //pDialog.setIndeterminate(false);
        //pDialog.setCancelable(false);
        //pDialog.show();   
    }

    /**
     * Get de json
     */
@Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
    // Hashmap voor listView
    final ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();

    // Maak een JSON Parser instance
    JSONParser jParser = new JSONParser();

    // Pakt JSON string uit URL
    JSONObject json = jParser.getJSONFromUrl(URL);


    try{
        // Pakt de Array van Nieuwsartikelen
        newsArray = json.getJSONArray(TAG_DATA);

        // Loop door alle Nieuwsartikels
        for(int i=0; i < newsArray.length(); i++){
            JSONObject c = newsArray.getJSONObject(i);

            // Het plaatsen van elk json item in variabele
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_CONTENT);
            String date = c.getString(TAG_DATE);
            //String introduction = c.getString(TAG_INTRODUCTION);
            String thumbnail = c.getString(TAG_THUMBNAIL);
            String linkedMedia = c.getString(TAG_LINKEDMEDIA);

            //String thumbnailName = c.getString(TAG_THUMBNAIL);
            //String thumbnailFormat = "http://iappministrator.com/mooiwark/media/%s";
            //String thumbnail = String.format(thumbnailFormat, thumbnailName);

            // maak een nieuwe HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // voeg elk item child node in de Hashmap -> value
            map.put(TAG_TITLE, title);
            map.put(TAG_CONTENT, content);
            map.put(TAG_DATE, date);
            //map.put(TAG_INTRODUCTION, introduction);
            map.put(TAG_THUMBNAIL, thumbnail);
            map.put(TAG_LINKEDMEDIA, linkedMedia);


            // voeg de HashList toe aan ArrayList
            newsList.add(map);

             // Click event for single list row
           mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
            //list.setOnItemClickListener(new OnItemClickListener() {

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

                    HashMap<String, String> map = newsList.get(position - 1);
                     Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);

                    //Intent in = new Intent(SingleMenuItemActivity.this, org.scout.android.library.LibraryDetail.class);
                    in.putExtra(TAG_TITLE, map.get(TAG_TITLE));
                    in.putExtra(TAG_CONTENT, map.get(TAG_CONTENT));                         
                    in.putExtra(TAG_DATE, map.get(TAG_DATE));
                    //in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
                    in.putExtra(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
                    in.putExtra(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));

                    startActivity(in);

                }
            });
        }
    } catch(JSONException e){
        e.printStackTrace();
    }
    return newsList;
}
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

    //De items worden ingeladen
    adapter=new LazyAdapter(Nieuws.this, result, R.layout.list_row, 
            new String[]{TAG_TITLE, TAG_CONTENT, TAG_DATE, TAG_THUMBNAIL}, new int[] {
            R.id.title, R.id.subtitle, R.id.date, R.id.list_image});   //TAG_INTRODUCTION mist nog 
    //list.setAdapter(adapter);
    mPullRefreshListView.setAdapter(adapter);

    // dismiss the dialog after getting all deelnemers
    //pDialog.dismiss();

    mPullRefreshListView.onRefreshComplete();

    super.onPostExecute(result);
        }
    }
}

在此活动中,它通常会在单击时加载内容。这个类是我试图变成片段类“SingleMenuItemActivity”类的类:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleMenuItemActivity  extends Fragment {

    // JSON node keys
    private static final String TAG_TITLE = "title";
    private static final String TAG_CONTENT = "content";
    private static final String TAG_DATE = "date";
    private static final String TAG_LINKEDMEDIA = "linkedMedia";
    //private static final String TAG_THUMBNAIL = "thumbnail";

    // Connection detector
    ConnectionDetector cd;

    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();

    /*@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);*/
   View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.single_list_item, container, false);

        return view;

        cd = new ConnectionDetector(getActivity().getApplicationContext());

        // Check for internet connection
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(getActivity(), "Internet Connectie Error", "Zorg voor een werkende internet connectie", false);
            // stop executing code by return
            return;
        }

        // getting intent data

        Intent in = getIntent().getExtras();

        //final String image_url = in.getStringExtra(TAG_THUMBNAIL);
        final String image_url = in.getStringExtra(TAG_LINKEDMEDIA);

        ImageView imgv = (ImageView) getView().findViewById(R.id.images_label);
        ImageLoader imageLoader = new ImageLoader(getActivity().getApplicationContext());
        imageLoader.DisplayImage(image_url, imgv);

        // Get JSON values from previous intent
        String title = in.getStringExtra(TAG_TITLE);
        String date = in.getStringExtra(TAG_DATE);
        String message = in.getStringExtra(TAG_CONTENT);
        //String images = in.getStringExtra(TAG_IMAGES);
        //Bitmap bitmap = in.getParcelableExtra(TAG_IMAGES);
        //ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);

        // Displaying all values on the screen
        TextView lblTitle = (TextView)getView().findViewById(R.id.title_label);
        TextView lblDate = (TextView) getView().findViewById(R.id.date_label);
        TextView lblMessage = (TextView) getView().findViewById(R.id.message_label);
        //ImageView lblImages = (ImageView) findViewById(R.id.images_label); 
        //TextView lblImages = (TextView) findViewbyId(R.id.images_label);



        // loader image
        //int loader = R.drawable.loader;
        System.out.println("Ja en nu werkt het niet meer");

        // image url
        //String image_url = "http://d24w6bsrhbeh9d.cloudfront.net/photo/5614379_460s.jpg";

       //ImageLoader imgLoader = new ImageLoader(getApplicationContext());
        //-imgLoader.DisplayImage(song.get(CustomizedListView.TAG_IMAGES), lblImages);
        System.out.println("Error? haha bam jammer dan:");
       //imgLoader.DisplayImage(images, lblImages);
        //System.out.println("Plaatjes?:"+ images);

        lblTitle.setText(title);
        lblDate.setText(date);
        lblMessage.setText(message);

        //lblImages.setImageURI(Uri.parse(images));

        //ImageLoader imageLoader = new ImageLoader(getApplicationContext());
        //imageLoader.DisplayImage(images,lblImages);

        //lblImages.setImageResource(images);
        //imageLoader.displayImage(images);
        //lblImages.setImageBitmap(bitmap);
        //lblImages.setImageResource(R.drawable.bitmap);
        //lblImages.setImageResource(images);
        /*if (d instanceof BitmapDrawable) {
            Bitmap bm = ((BitmapDrawable)d).getBitmap();
            //Maybe more code here?
            lblImages.setImageBitmap(bm);
    }*/
        //lblImages.setImageResource(images);
        //lblImages.DisplayImage(images);
        //lblImages.DisplayImage(images);
    }
}

现在我正在进入我不理解的部分,我的 Intent in = getIntent() 不起作用我得到错误。有人可以指导我将代码从活动转换为片段吗?非常感谢

截屏: 在此处输入图像描述

左“新闻类”右“SingleMenuItemActivity”

当我单击左侧类中的 onclick 时出错了。

4

2 回答 2

1

首先,我建议您为列表使用 ListFragment 并为 onclick 事件定义一个侦听器(此侦听器可能是您的 Nieuws 活动)。

然后你需要有2个布局。经典的一个片段:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/onepane_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
</LinearLayout>

另一个有两个片段:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:id="@+id/towpane_layout">
    <fragment android:id="@+id/listFragment"
              android:layout_height="fill_parent"
              android:name="com.example.MyListFragment"
              android:layout_width="400dp"
              android:layout_marginRight="10dp"/>
    <fragment android:id="@+id/displayFragment"
              android:layout_height="fill_parent"
              android:name="com.example.MyDisplayFragment"
              android:layout_width="fill_parent" />
</LinearLayout>

在您的 Nieuws Activity 中,您将检查加载的布局是否有两个片段,如果没有,您将使用片段管理器加载 ListFragment

//Check that the activity is not using the layout with fragment;
        if(findViewById(R.id.onepane_layout) != null) {
            if (savedInstanceState != null) {
                return;
            }
            MyListFragment lFragment = new MyListFragment ();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            lFragment .setArguments(getIntent().getExtras());

             getFragmentManager().beginTransaction()
             .add(R.id.onepane_layout, lFragment ).commit();
        }

然后在您的项目选择方法中,如果您处于单窗格模式,您需要再次加载显示片段:

MyDisplayFragment dispFrag = (MyDisplayFragment)
                getSupportFragmentManager().findFragmentById(R.id.displayFragment);



 if (dispFrag != null) {
        // If display frag is available, we're in two-pane layout...

        // Call a method in the DisplayFragment to update its content
        dispFrag.updateView(position);

    } else {
        // If the frag is not available, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        MyDisplayFragment newFragment = new MyDisplayFragment ();
        Bundle args = new Bundle();
        args.putInt(MyDisplayFragment.ARG_POSITION, position);
        newFragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }

还有更多要解释的,但这是基础知识。您可能需要检查这两个有用的链接:http: //developer.android.com/training/multiscreen/adaptui.h​​tml

http://developer.android.com/training/basics/fragments/fragment-ui.html

您还需要处理屏幕旋转。

于 2013-02-06T15:47:37.360 回答
0

在你的FragmentActvity,而不是创建Intent,你需要创建对象Bundle

mPullRefreshListView.setOnItemClickListener(new OnItemClickListener(){
    //list.setOnItemClickListener(new OnItemClickListener() {

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

        HashMap<String, String> map = newsList.get(position - 1);
        Bundle in = new Bundle();
        in.putString("TAG_TITLE",map.get(TAG_TITLE));

        in.putString(TAG_TITLE, map.get(TAG_TITLE));
        in.putString(TAG_CONTENT, map.get(TAG_CONTENT));                         
        in.putString(TAG_DATE, map.get(TAG_DATE));
        //in.putExtra(TAG_INTRODUCTION, map.get(TAG_INTRODUCTION));
        in.putString(TAG_THUMBNAIL, map.get(TAG_THUMBNAIL));
        in.putString(TAG_LINKEDMEDIA, map.get(TAG_LINKEDMEDIA));
        SingleMenuItemActivity singleMenu = new SingleMenuItemActivity(in); 
        FragmentManager fragmentManager=getFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.add(android.R.id.content, SingleMenuItemActivity);
        fragmentTransaction.addToBackStack("");//if needed
        fragmentTransaction.commit();



    }
});
}

在你的SingleMenuItemActivity类中创建构造函数,它接受参数一个Bundle对象

public DetailActvity(Bundle bundle)
    {
    this.bundle=bundle;//update global Bundle object
    }


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

        mView= inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container,false);

        imgView = (ImageView)mView.findViewById(R.id.imageView1);

        tvDetail = (TextView)mView.findViewById(R.id.tvDetail);
        String detail=bundle.getString("KEY");
        tvDetail.setText(detail);
        String image=bundle.getString("KEY");
        return mView;

    }
于 2013-02-06T15:53:45.103 回答