Ориентация ListView - PullRequest
       48

Ориентация ListView

0 голосов
/ 08 декабря 2018

У меня проблемы с восстановлением изменений, внесенных в ListView (удаленные элементы и т. Д.) После изменения ориентации.Цель проекта - сохранить элементы одинаковыми, независимо от того, какая ориентация изменилась.В дополнение, хотя это и не требуется, я также пытаюсь выяснить, как получить первые четыре TextView ниже (которые меняются в зависимости от того, какой элемент нажат) для того, чтобы оставаться неизменным после изменения ориентации (Примечание: описание TextView должно быть доступно толькокогда ориентация установлена ​​на ландшафт).Это не так важно, хотя.Что я могу сделать, чтобы сделать эту работу?

MainActivity:

public class MainActivity extends AppCompatActivity {


    ListView listView;
    ArrayList<Flick> flicks;
    TextView description;
    TextView year;
    TextView director;
    TextView rating;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listView);
        description = findViewById(R.id.description);
        year = findViewById(R.id.year);
        director = findViewById(R.id.director);
        rating = findViewById(R.id.rating);
        flicks = new ArrayList<>();
        flicks.add(new Flick("Wizard of Oz", "Metro-Goldwyn-Mayer", "VARIOUS", "1939", "It is in my honest and personal opinion that this movie his highly overrated. Although I do acknowledge and admire it's contributions to modern cinema, I find the movie to be overly jolly and too reliant on escapist themes.", "98"));
        flicks.add(new Flick("Star Wars", "LucasFilm", "George Lucas", "1977", "Definitely lives up to its iconic status. Star Wars continues to be regarded as one of the most cutting-edge films of the 20th Century, as it so brilliantly demonstrates through its mixture of multiple genres with hardcore thematic complexity, comprising in what very well may be the greatest epic since the 70s", "93"));
        flicks.add(new Flick("Psycho", "Paramount", "Alfred Hitchcock", "1960", "Hitchcock is truly the master of suspense critics make him out to be. Throughout this movie, despite I having already some concept of the twists in this movie, found Hitchcock's choices in editing and composition to be as bold as it is jarring.", "97"));
        flicks.add(new Flick("King Kong", "RKO Pictures", "Merian C. Cooper & Ernest B. Schoedsack", "1933", "", "98"));
        flicks.add(new Flick("2001: A Space Odyssey", "Metro-Goldwyn-Mayer", "Stanley Kubrick", "1968", "The first time viewing this, I knew right then and there that this was my all-time favorite movie and that Kubrick would forever be my favorite director. Never had I ever been so enganged in such existentialist themes, supported by Kubrick's glowing cinematography and sprawling soundtrack", "93"));
        flicks.add(new Flick("Citizen Kane", "RKO Pictures", "Orson Welles", "1941", "The title of 'Citizen Kane' has become synonymous with excellence, or, rather, being the most perfect representation of something; with that in mind, 'Citizen Kane' truly is the 'Citizen Kane' of cinema. Renaissance man Orson Welles demonstrates his incredible acting ability while introducing many elements of filmmaking which would become staples of films today: particularly the inclusion of heavy motifs, the presence of which in prior films was arguably lackluster.", "100"));
        flicks.add(new Flick("Snow White and the Seven Dwarfs", "Walt Disney Pictures", "VARIOUS", "1937", "The world today would most likely be a lot more smug if Walt Disney did not have the guts to make the first feature-length animated film. 'Snow White' enable the inclusiveness of cinema to all filmgoers, although the age of time has not given it any favors, as it seems.", "98"));
        flicks.add(new Flick("Casablanca", "Warner Bros.", "Michael Curtiz", "1942", "It's hard to believe that this movie's acclaim was completely accidental. Having been made in an era where movies received funding like candy in order to keep up in the industry, this 'diamond in the rough' was responsible for the inclusion of both the tragic love story and connections to politics in a movie.", "97"));
        flicks.add(new Flick("The Godfather", "Paramount", "Francis Ford Coppola", "1972", "The Coppolas are a much beloved family in the world of Hollywood; their success began with 'The Godfather.' Coppola's masterpiece reinvented the gangster genre, displaying feelings such as remorse, regret disdain, and sympathy within its characters, all with the use of innovations such as the use of the Italian languange and Gordon Willis's pioneering cinematography.", "98"));
        flicks.add(new Flick("Jaws", "Universal", "Steven Spielberg", "1975", "The 'prototypical' blockbuster, Jaws introduced a multi-trillion dollar industry that has become immensely popular today. Spielberg's divergent practices soon became the basis for many popular films (mostly blockbusters) today.", "97"));

        final CustomAdapter customAdapter = new CustomAdapter(this, R.layout.custom_layout, flicks);
        listView.setAdapter(customAdapter);

        listView.setClickable(true);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                director.setText("Director: " + customAdapter.getItem(position).getDirector());
                rating.setText("Rating: " + customAdapter.getItem(position).getRating());
                year.setText("Year Released: " + customAdapter.getItem(position).getYear());
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
                    description.setText("Description: " + customAdapter.getItem(position).getThoughts());

            }
        });



    }


    public class CustomAdapter extends ArrayAdapter<Flick> {
        Context context;
        int resource;
        List<Flick> list;

        public CustomAdapter(@NonNull Context context, int resource, @NonNull List<Flick> objects) {
            super(context, resource, objects);
            this.context = context;
            this.resource = resource;
            list = objects;
        }


        @NonNull
        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            final View adapterView = layoutInflater.inflate(resource, null);


            TextView title = adapterView.findViewById(R.id.title);
            ImageView imageView = adapterView.findViewById(R.id.imageView);
            Button remove = adapterView.findViewById(R.id.remove);
            title.setText(list.get(position).getTitle());
            switch (list.get(position).getStudio()) {
                case "Warner Bros.":
                    imageView.setImageResource(R.drawable.warnerbros);
                    break;
                case "Paramount":
                    imageView.setImageResource(R.drawable.paramount);
                    break;
                case "Universal":
                    imageView.setImageResource(R.drawable.universal);
                    break;
                case "LucasFilm":
                    imageView.setImageResource(R.drawable.lucasfilm);
                    break;
                case "RKO Pictures":
                    imageView.setImageResource(R.drawable.rko);
                    break;
                case "Walt Disney Pictures":
                    imageView.setImageResource(R.drawable.disney);
                    break;
                case "Metro-Goldwyn-Mayer":
                    imageView.setImageResource(R.drawable.mgm);
                    break;
            }
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(position);

                    notifyDataSetChanged();
                }
            });
            return adapterView;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        Parcelable listState = listView.onSaveInstanceState(outState);
        outState.putParcelable("listState", listState);
        listView.getFirstVisiblePosition();

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

    }
}

1 Ответ

0 голосов
/ 08 декабря 2018

В вашем AndroidManifest.xml вы можете добавить эту строку к вашей соответствующей деятельности:

android:configChanges="orientation|screenSize"

Пример:

<activity android:name=".MainActivity"
            android:configChanges="orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Добавив эту строку, вы можете самостоятельно обрабатывать изменения ориентации и останавливаться.действие от перезапуска и обновления ресурсов само по себе.

В своей деятельности вы можете переопределить метод onConfigurationChanged и обработать ваши изменения, например:

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //do something here like make description visible
        } else {
            //do something here like make description invisible
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...