簡體   English   中英

更改設備方向時,如何確保列表視圖元素不會消失?

[英]How do I ensure that my list view element do not disappear when I change the orientation of my device?

我正在構建一個顯示您搜索的書的詳細信息的應用。 問題在於,每次更改設備的方向時,列表視圖元素都會消失。 我需要幫助,以使它們不會消失。 我覺得我需要使用Loader,但是我不知道如何實現它。 這是我的活動。

主要活動 :-

package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private BookAdapter mAdapter;
    EditText searchtext;
    ListView earthquakeListView;
    TextView empty;
    TextView authorcheck;
    TextView titlecheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        earthquakeListView = (ListView) findViewById(R.id.listView);
        mAdapter = new BookAdapter(this, new ArrayList<Book>());
        earthquakeListView.setAdapter(mAdapter);
        searchtext = (EditText) findViewById(R.id.editText);
        empty = (TextView) findViewById(R.id.textView);
        earthquakeListView.setEmptyView(empty);


    }




    public void searchclick(View view) {
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            String parturl = searchtext.getText().toString();
            parturl = parturl.replaceAll("\\s","");
            StringBuilder urlbuilder = new StringBuilder();
            urlbuilder.append("  https://www.googleapis.com/books/v1/volumes?q=");
            urlbuilder.append(parturl);
            urlbuilder.append("&maxResults=5");
            String url = urlbuilder.toString();
            BookAsyncTask task = new BookAsyncTask();
            task.execute(url);        }
        else{
            Toast.makeText(getApplicationContext(), "You are not connected to the internet",
                    Toast.LENGTH_LONG).show();
        }

    }
    private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
        @Override
        protected List<Book> doInBackground(String... urls) {
            // Don't perform the request if there are no URLs, or the first URL is null
            if (urls.length < 1 || urls[0] == null) {
                return null;
            }
            List<Book> result = QueryUtils.fetchBookData(urls[0]);
            return result;
        }
        @Override
        protected void onPostExecute(List<Book> data) {
            mAdapter.clear();
            if (data != null && !data.isEmpty()) {
                mAdapter.addAll(data);
            }
        }
    }
}

QueryUtils:-

package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by visha on 14-10-2016.
 */
public final class QueryUtils {
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();
    private QueryUtils() {
    }
    public static List<Book> fetchBookData(String requestUrl) {
        URL url = createUrl(requestUrl);
        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem making the HTTP request.", e);
        }
        List<Book> Books = extractFeatureFromJson(jsonResponse);
        return Books;
    }
    private static URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Problem building the URL ", e);
        }
        return url;
    }
    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        if (url == null) {
            return jsonResponse;
        }
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return jsonResponse;
    }
    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }
    private static List<Book> extractFeatureFromJson(String BookJSON) {
        if (TextUtils.isEmpty(BookJSON)) {
            return null;
        }
        List<Book> Books = new ArrayList<>();
        try {
            JSONObject baseJsonResponse = new JSONObject(BookJSON);
            JSONArray BookArray = baseJsonResponse.getJSONArray("items");
            for (int i = 0; i < BookArray.length(); i++) {
                JSONObject currentBook = BookArray.getJSONObject(i);
                JSONObject properties = currentBook.getJSONObject("volumeInfo");
                String author;
                if(properties.has("authors")) {
                     author = properties.getString("authors");
                }
                else {
                     author = "";
                }
                String title = properties.getString("title");
                Book Book = new Book(author, title);
                Books.add(Book);
            }
        } catch (JSONException e) {
            Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
        }
        return Books;
    }
}

您需要重寫Activity類的onSaveInstanceState和onRestoreInstanceState方法。

在onSaveInstanceState中,將列表數據保存到Bundle中。

在onRestoreInstanceState中,使用Bundle數據還原列表,然后重新創建列表適配器。

干杯!!!

如果您在活動橫向模式下沒有其他布局,則只需放置android:configChanges="orientation|screenLayout|screenSize"為您完成工作。

例:

 <activity
        android:name=".MainActivity"
        android:configChanges="orientation|screenLayout|screenSize" />

如果橫向模式的布局確實不同,則需要覆蓋savedInstanceState並相應地在OnCreate保存和還原列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM