【问题标题】:2 Refreshing Issues within a ListFragment2 ListFragment 中的刷新问题
【发布时间】:2011-09-01 23:08:06
【问题描述】:

我的 ListFragment 有两个问题: 我想在单击 XML 文件中定义的按钮后刷新 ListFragment。我最初在 TitlesFragment 的 AsyncTask 中加载 DataAdapter 的数据。

我还没有找到一种方法来为可以访问 AsyncTask 的按钮创建代码 - 并刷新我的 TitlesFragment

另外一点:每次我更改手机的方向时,Listfragment 都会自行更新,这绝对不是我想要的行为。

public class ClosestPlaces extends FragmentActivity {

private static KantinenListe kantinen;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_ACTION_BAR);        
    setContentView(R.layout.kantinen_results);

}   

/**
 * This is the "top-level" fragment, showing a list of items that the
 * user can pick.  Upon picking an item, it takes care of displaying the
 * data to the user as appropriate based on the currrent UI layout.
 */

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;


    private class BuildKantinen extends AsyncTask<String, Integer, KantinenListe>   {

        private KantinenListe kantinen;


        @Override
        protected KantinenListe doInBackground(String... params) {
            try{

                Gson gson = new Gson();             
                // SOAP Test
                String NAMESPACE = "http://tempuri.org/";
                String METHOD_NAME = "fullSyncGPS";
                String SOAP_ACTION = "http://tempuri.org/IDatenService/fullSyncGPS";
                String URL = "http://webserviceURL?wsdl";

                SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);

                PropertyInfo pi = new PropertyInfo();
                request.addProperty("radius",10);
                request.addProperty("lat", "14.089201");
                request.addProperty("lng", "02.136459");
                request.addProperty("von", "01.09.2011");
                request.addProperty("bis", "01.09.2011");

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);        

                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

                String resultData = result.toString(); 


                resultData = "{\"meineKantinen\":"+resultData+"}";
                this.kantinen = gson.fromJson(resultData, KantinenListe.class);
                Log.i("test", "blubber" );
            }
            catch(Exception e)
            {
                 e.printStackTrace();
            }
                return this.kantinen;

        }

        @Override
        protected void onPostExecute(KantinenListe result) {
            // populate the List with the data
            Log.i("test", "postexecute" );
            setListAdapter( new MenuAdapter(getActivity(), R.layout.simple_list_item_checkable_1, kantinen.getMeineKantinen()));
        }
    }


    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        new BuildKantinen().execute("test");                       

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);            
    }

    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index) {
        mCurCheckPosition = index;

            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Log.i("Test",Integer.toString(index));
            Intent intent = new Intent();
            intent.setClass(getActivity(), BeAPartner.class);
            startActivity(intent);
    }
}

public static class MenuAdapter extends ArrayAdapter {

    private LayoutInflater mInflater;
    private List<Kantine> items;
    private Context context;

    public MenuAdapter(Context context, int textViewResourceId, List<Kantine> items) {
        super(context, textViewResourceId);
        mInflater = LayoutInflater.from(context);
        this.items = items;
        this.context = context;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.menu_row, parent, false);
            holder = new ViewHolder();
            holder.color = (TextView) convertView.findViewById(R.id.color);
            holder.title = (TextView) convertView.findViewById(R.id.detail);
            holder.subdetail = (TextView) convertView.findViewById(R.id.subdetail);

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

        // Fill in the actual story info
        Kantine s = items.get(position);

        s.setName( Html.fromHtml(s.getName()).toString() );
        if (s.getName().length() > 35)
            holder.title.setText(s.getName().substring(0, 32) + "...");
        else
            holder.title.setText(s.getName());

        Log.i("display", "Here I am");
        return convertView;
    }


 }
    static class ViewHolder {
        TextView color;
        TextView title;
        TextView subdetail;
    }   

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    要阻止 Activity 重新启动,您只需在运行 Fragment 的 Activity 上设置 android:configChanges 属性即可。

        android:configChanges="orientation"
    

    告诉系统在方向改变时不重启活动只是为了改变方向的设置。

    对于按钮,使用属性 android:onClick="myFunction" 在 XML 中设置您的点击监听器。然后在你的片段中定义这个函数:

        public void myFunction(View v)
        {
                 new myAsync.execute('test');       
        }
    

    【讨论】:

    • 这基本上意味着我需要创建一个“单一”异步类。由于我无法引用“子类”异步任务。正确的?但是,如果它不再是 TitleFragment 的子类,我无法从原始 FragmentActivity 中引用“setListAdapter”
    • 如果你也有对外部类的引用,你也可以引用一个子类。好消息是 FragmentActivity 存储了对给定片段的引用,您可以使用它来创建新的 BuildKantinen 异步对象。基本上类似于“fragmentReference.new BuildKantinen().execute('test');”。 O 还必须将片段引用转换为 TitlesFragment,因为常规 ListFragment 没有内部类 BuildKantinen。
    【解决方案2】:

    当您更改手机方向时,它会重新启动活动。您需要持久保存的任何内容都需要保存在 onSaveInstanceState(Bundle savedInstanceState) 中并使用 onRestoreInstanceState(Bundle savedInstanceState) 进行恢复。

    至于单击按钮时更新数据,请尝试在适配器上调用 notifyDataSetChanged()。如果这不起作用,您可能只需要再次运行您的 asynctask。

    【讨论】:

    • 但是如何在片段之外(基本上在活动中)调用 AsyncTask 呢?
    • 你需要以某种方式抓取片段。您是否在布局文件中定义它?在示例中,您将在 onCreate 方法中看到类似这样的内容:if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {ArrayListFragment list = new ArrayListFragment();getSupportFragmentManager().beginTransaction().add(android.R.id.content, list).commit();} 在这种情况下,'list' 是对片段的引用,所以如果你有一个 update() 函数在您的片段中,您可以调用 list.update() (对不起格式......无法弄清楚)
    • 我正在创建一个 XML 文件的片段。但我就是无法让所有这些方法发挥作用:(
    【解决方案3】:

    好的,我认为在新答案中发布可能的解决方案是最佳做法 - 出于可读性的明显原因:

    public void reload(View v)
    {
        if (getSupportFragmentManager().findFragmentById(R.id.titles) != null) { 
                Fragment titles = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.titles);
                //recreate the fragment
                titles.onActivityCreated(null);
        }
    }
    

    正是我想要的(重新加载数据)!但是......我认为这个解决方案的内存占用可能很糟糕。

    【讨论】:

    • 重新创建片段似乎有点矫枉过正。如果您有对片段的引用(在本例中为“标题”),您应该能够调用其中的任何方法或函数。只需在其中创建一个函数来重新查询您的数据并更新适配器。
    • 确实,如果您使用的是 LoaderManager,您只需重新启动加载程序,但在您的情况下,您需要手动重新加载数据。
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多