0

スタイル(または名前がわからないもの)を作成して再利用したいのですが、画面には100を超えるアイテムがあり、各アイテムには画像とテキストビューが含まれていますが、それは良いとは思いません私のxmlファイルで100のレイアウトを作成する方法は、1回(画像とテキストビューを保持する)を作成してから、アクティビティでそれを再開する方法があると思います。何か提案はありますか?

4

1 に答える 1

1

Androidからのフラグメントへのリンクは次のとおりです。以下はフラグメントを使用したプロジェクトへのコードです。以下のコードもuniversalimageloaderActionBarSherlockを使用していますが、アクションバーはあまり使用していません。このコードは、フラグメントとメインのSherlockFragmentActivityの間で通信するインターフェースも使用します。使用されている2つの異なるフラグメントを示しました。あるサイトまたは別のサイトからデータをロードできるフラグメントと、フラグメント制御アクティビティを使用したインターフェイス設定からデータを取得する詳細フラグメントを一覧表示します。

詳細フラグメント

import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class DetailsFrag extends SherlockFragment {
public static final String TAG = "detailsfrag";
private boolean typeFlag;
private GetData gd;
private DisplayImageOptions dio = null;
private ImageLoader il;
private ImageView image;
private TextView name;
private TextView data_box_1;
private TextView data_box_2;
private HashMap<String, Object> fragData;

static DetailsFrag newInstance() {
    DetailsFrag frag = new DetailsFrag();

    return frag;
}

public interface GetData {
    public HashMap<String, Object> getData();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        gd = (GetData) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement GetData");
    }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflate, ViewGroup container,
        Bundle savedInstanceState) {
    setRetainInstance(true);
    setHasOptionsMenu(true);
    il = ImageLoader.getInstance();
    dio = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.kzfr_logo).cacheInMemory()
            .cacheOnDisc().displayer(new RoundedBitmapDisplayer(20))
            .build();
    View result = inflate.inflate(R.layout.details_frag, container, false);
    image = (ImageView) result.findViewById(R.id.image);
    data_box_1 = (TextView) result.findViewById(R.id.data_box_1);
    data_box_2 = (TextView) result.findViewById(R.id.data_box_2);
    name = (TextView) result.findViewById(R.id.name);

    fragData = gd.getData();

    String imagePath = (String) fragData.get("image");
    il.displayImage(imagePath, image, dio);
    Toast.makeText(getSherlockActivity(), "Image path " + imagePath,
            Toast.LENGTH_LONG).show();
    String title = (String) fragData.get("title");
    name.setText(title);
    String times = (String) fragData.get("times");
    data_box_1.setText(times);
    String data2 = (String) fragData.get("short_description");
    data_box_2.setText(data2);
    return result;
}

}

これがリストフラグメントです

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;

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

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockListFragment;

public class ListFrag extends SherlockListFragment {
public static final String TAG = "listfrag";
private boolean typeFlag;
private String mainUrl;
private SetDetails sd;
private List<HashMap<String, Object>> data;

static ListFrag newInstance(boolean type) {
    ListFrag frag = new ListFrag();
    Bundle args = new Bundle();
    args.putBoolean("type", type);
    frag.setArguments(args);
    return frag;
}

public interface SetDetails {
    public void setDetails(HashMap<String, Object> details);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        sd = (SetDetails) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement setDetails");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    sd.setDetails(data.get(position));
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    // set the type of the listview. Hosts or Programs.
    setType();
    if (typeFlag) {
        mainUrl = "http://website.org/api/dataset1";
    } else {
        mainUrl = "http://website.org/api/dataset2";
    }

    // begin a download task to download the data needed to populate the
    // correct list view.
    if (!checkAdapter()) {
        DownloadTask dlTask = new DownloadTask();
        dlTask.execute(mainUrl);
    } else {
        SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
        adapter.notifyDataSetChanged();
    }
}

public boolean checkAdapter() {
    SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
    if (adapter != null)
        return true;
    else
        return false;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    // SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
    // if (adapter != null)
    // adapter.notifyDataSetChanged();
}

private void setType() {
    Bundle args = this.getArguments();
    typeFlag = args.getBoolean("type");
}

private boolean checkType() {
    return typeFlag;
}

/*
 * This method connects to the specified url and returns data ready to be
 * parsed.
 */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream in = null;

    try {
        URL url = new URL(strUrl);
        URLConnection urlConnect = (URLConnection) url.openConnection();
        urlConnect.connect();

        in = urlConnect.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                urlConnect.getInputStream()));

        StringBuffer sb = new StringBuffer();

        String line = "";

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        data = sb.toString();
        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        in.close();
    }
    return data;
}

private class DownloadTask extends AsyncTask<String, Integer, String> {
    String data = null;

    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {

        ListViewLoaderTask lvLoader = new ListViewLoaderTask();
        lvLoader.execute(result);
    }
}

private class ListViewLoaderTask extends
        AsyncTask<String, Void, ImageLoaderListAdapter> {
    ImageLoaderListAdapter adapter = null;
    int count;
    HashMap<String, Object> hm = null;
    String imgUrl = null;
    String url = "http://website.org/u/img/original/";

    @Override
    protected ImageLoaderListAdapter doInBackground(String... jsonStr) {
        List<HashMap<String, Object>> things = null;
        JSONArray jArray = null;
        try {
            jArray = new JSONArray(jsonStr[0]);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String[] from = { "title", "image", "short_description" };
        int[] to = { R.id.program_title, R.id.program_image,
                R.id.short_description };
        if (checkType()) {

            data1JSONParser data1Parser = new data1JSONParser();
            try {
                things = data1Parser.parse(jArray);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }

        } else {

            data2JSONParser data2Parser = new data2JSONParser();
            try {
                things = data2Parser.parse(jArray);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }

        count = things.size();
        for (int i = 0; i < count; i++) {
            hm = (HashMap<String, Object>) things.get(i);
            imgUrl = (String) hm.get("image");
            if (!imgUrl.equalsIgnoreCase("false")) {
                imgUrl = url + imgUrl;
                hm.put("image", imgUrl);

            }
        }
                    //ImageLoaderListAdapter is a Simple List Adapter that uses Universal Image
                    //Loader to load its images if possible.
        adapter = new ImageLoaderListAdapter(getSherlockActivity()
                .getBaseContext(), things, R.layout.rowlayout, from, to);
        data = things;
        return adapter;
    }

    @Override
    protected void onPostExecute(ImageLoaderListAdapter adapter) {

        setListAdapter(adapter);
        ImageLoaderListAdapter ad = (ImageLoaderListAdapter) getListAdapter();
        ad.notifyDataSetChanged();
    }
}

}

これがフラグメント制御アクティビティIです

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

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.appdomum.doublea.DayFragment.UpdateList;
import com.appdomum.doublea.DetailsFrag.GetData;
import com.appdomum.doublea.ListFrag.SetDetails;
import com.appdomum.doublea.RadioStream.OnProgramSelectedListener;
import com.appdomum.doublea.ScheduleFrag.UpdateSchedule;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class FragmentControl extends SherlockFragmentActivity implements
    GetData, SetDetails {
protected ImageLoader imageLoader = ImageLoader.getInstance();
    
private ListFrag data1Frag;
private ListFrag data2Frag;
private DetailsFrag detailsFrag;
private Fragment visible;
private Fragment mVisibleCached;
private boolean instanceStateSaved;
private HashMap<String, Object> details = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment_control);
    setupFragments();
    ImageLoaderConfiguration config = ImageLoaderConfiguration
            .createDefault(getApplicationContext());
    imageLoader.init(config);
}

public void setupFragments() {
    final FragmentManager fm = getSupportFragmentManager();
    final FragmentTransaction ft = fm.beginTransaction();

    data1Frag = ((ListFrag) fm.findFragmentByTag("data1".TAG));
    if (data1Frag == null) {
        data1Frag = ListFrag.newInstance();
        ft.add(R.id.fragment_container, data1Frag , "data1".TAG);
    }
    visible = data1Frag ;

    ft.commit();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    visible = mVisibleCached;
    
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getSupportMenuInflater()
            .inflate(R.menu.activity_fragment_control, menu);
    return true;
}

@Override
protected void onDestroy() {
    if (!instanceStateSaved) {
        imageLoader.stop();
    }
    super.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    instanceStateSaved = true;
}

public void showFragment(int fragIn) {
    int inFrag = fragIn;
    final FragmentManager fm = getSupportFragmentManager();
    final FragmentTransaction ft = fm.beginTransaction();
    
    ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    if (visible != null) {

        ft.hide(visible);
        mVisibleCached = visible;

    }
    switch (fragIn) {
    case 0:
        data1Frag = ((ListFrag) fm.findFragmentByTag(data1));
        if (data1Frag == null) {
            data1Frag = ListFrag.newInstance(false);
            ft.replace(R.id.fragment_container, data1Frag ,
                    "data1");
        } else {
            ft.replace(R.id.fragment_container, data1Frag ,
                    "data1");

            if (!data1Frag .isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = data1Frag ;
        break;
    case 1:
        data2Frag= ((ListFrag) fm.findFragmentByTag("data2"));
        if (data2Frag== null) {
            data2Frag= ListFrag.newInstance(true);
            ft.replace(R.id.fragment_container, data2Frag, "data2");
        } else {
            ft.replace(R.id.fragment_container, data2Frag, "data2");

            if (!data2Frag.isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = data2Frag;
        break;
    case 2:
        detailsFrag = ((DetailsFrag) fm.findFragmentByTag(DetailsFrag.TAG));
        if (detailsFrag == null) {
            detailsFrag = DetailsFrag.newInstance();
            ft.replace(R.id.fragment_container, detailsFrag,
                    DetailsFrag.TAG);
        } else {
            ft.replace(R.id.fragment_container, detailsFrag,
                    DetailsFrag.TAG);
            if (!detailsFrag.isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = detailsFrag;
        break;
    }
    ft.commit();
}

@Override
public HashMap<String, Object> getData() {
    return details;
}

@Override
public void setDetails(HashMap<String, Object> data) {
    this.details = data;
    showFragment(2);
}

}

フラグメントコントロールのレイアウトは次のとおりです

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentControl" >

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

詳細フラグメントのレイアウト

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/woodtileback"
android:padding="10dp" >

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:paddingBottom="5dip"
    android:paddingTop="10dip"
    android:textAlignment="center" />

<ImageView
    android:id="@+id/image"
    android:layout_width="300dip"
    android:layout_height="300dip"
    android:layout_below="@id/name"
    android:layout_centerHorizontal="true"
    android:clickable="true"
    android:contentDescription="@string/programdescription" />

<TextView
    android:id="@+id/data_box_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/image"
    android:layout_centerHorizontal="true"
    android:padding="5dp"
    android:textAlignment="center" />

<TextView
    android:id="@+id/data_box_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/data_box_1"
    android:layout_centerHorizontal="true"
    android:padding="5dp"
    android:textAlignment="center" />

</RelativeLayout>

リスト行のレイアウト

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="5dp" >

<ImageView
    android:id="@+id/program_image"
    android:layout_width="100dip"
    android:layout_height="100dip"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/programdescription"
    android:padding="5dp" />

<LinearLayout
    android:id="@+id/details"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/program_image"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/program_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left" />

    <TextView
        android:id="@+id/short_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left" />
</LinearLayout>

</RelativeLayout>
于 2013-01-19T22:29:01.513 に答える