Что я должен сделать, чтобы написать алгоритм, который автоматически редактирует мои XML-файлы - PullRequest
0 голосов
/ 01 июля 2019

Я пытаюсь сделать свое первое приложение для Android. Я имею в виду, что могу очень быстро понять, и именно поэтому я делаю свой последний шаг в своем первом приложении для Android. Я хочу, чтобы некоторые XML-файлы автоматически редактировались алгоритмом. Я специально хочу, чтобы текстовое представление в моем XML-файле было отредактировано ...

Я написал приложение для мероприятий в моем Collage Club, и это потому, что оно должно редактироваться каждые две недели. Данные и имя очень важны и, конечно, комната, но в большинстве случаев это одно и то же ...

<?xml version="1.0" encoding="utf-8"?>
<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"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:background="@color/darkgrey">

    <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Termine"
                    android:textSize="30sp"
                    android:textColor="@color/colorAccent"
                    android:layout_gravity="center_horizontal"
                    android:layout_centerHorizontal="true"
                    android:layout_centerVertical="true" />

            <android.support.v7.widget.CardView

                    android:layout_width="match_parent"
                    android:layout_height="173dp"
                    app:cardCornerRadius="8dp"
                    android:layout_marginTop="20dp"
                    android:layout_marginLeft="30dp"
                    android:layout_marginRight="30dp"
                    >

                <Button
                        android:text="Mehr infos"
                        android:layout_width="120dp"
                        android:layout_height="35dp"
                        android:id="@+id/button1"
                        android:layout_weight="1"
                        android:layout_marginTop="130dp"
                        android:layout_marginRight="170dp"
                        android:background="@drawable/buttonshape"
                        android:shadowColor="#A8A8A8"
                        android:shadowDx="0"
                        android:shadowDy="0"
                        android:shadowRadius="5"/>


                <LinearLayout android:layout_height="match_parent"
                              android:layout_width="match_parent"
                              android:background="@color/maincolor">

                </LinearLayout>

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="- 29.06.19"
                          android:textSize="24dp" />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="Sitzung: H-E.51"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"/>

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="Juni22, 2019"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"
                          android:layout_marginRight="20dp"
                          android:layout_marginLeft="270dp" />

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView

                    android:layout_width="match_parent"
                    android:layout_height="173dp"
                    app:cardCornerRadius="8dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="30dp"
                    android:layout_marginRight="30dp"
                    >

                <LinearLayout android:layout_height="match_parent"
                              android:layout_width="match_parent"
                              android:background="@color/colorPrimaryDark"

                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="- 13.07.19"
                          android:textSize="24dp"
                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="Sitzung: H-E.51"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"

                        />
                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="July13, 2019"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"
                          android:layout_marginRight="20dp"
                          android:layout_marginLeft="270dp"

                        />

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView

                    android:layout_width="match_parent"
                    android:layout_height="173dp"
                    app:cardCornerRadius="8dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="30dp"
                    android:layout_marginRight="30dp"
                    >

                <LinearLayout android:layout_height="match_parent"
                              android:layout_width="match_parent"
                              android:background="@color/yellow"

                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="- 27.07.19"
                          android:textSize="24dp"
                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="Sitzung: H-E.51"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"

                        />
                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="July27, 2019"
                          android:textSize="12dp"
                          android:layout_marginTop="40dp"
                          android:layout_marginRight="20dp"
                          android:layout_marginLeft="270dp"

                        />

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView

                    android:layout_width="match_parent"
                    android:layout_height="173dp"
                    app:cardCornerRadius="8dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="30dp"
                    android:layout_marginRight="30dp"
                    >

                <LinearLayout android:layout_height="match_parent"
                              android:layout_width="match_parent"
                              android:background="@color/maincolor"

                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="unwichtig"
                          android:textSize="24dp"
                        />

                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="Sitzung: H-E.51"
                          android:textSize="16dp"
                          android:layout_marginTop="40dp"

                        />
                <TextView android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:textColor="@color/white"
                          android:text="August10, 2019"
                          android:textSize="12dp"
                          android:layout_marginTop="40dp"
                          android:layout_marginRight="20dp"
                          android:layout_marginLeft="270dp"

                        />

            </android.support.v7.widget.CardView>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

Надеюсь, вы понимаете, что я хочу сделать ... что каждые две недели его нужно менять еще на две даты через 2 недели и так далее ... Имя может быть таким же, но я хочу знать, как я нужно написать код и что я должен для этого сделать .... Большое спасибо всем, кто хочет помочь ....

Это сложно, но именно поэтому я здесь Спасибо

1 Ответ

0 голосов
/ 04 июля 2019

Я думаю, вы ищете что-то подобное.Следующий код получит текущую системную дату, отобразит ее в TextView и сохранит ее, используя Shared Preferences .Также при будущих запусках приложения этот код будет рассчитывать дни между текущей датой (датой, когда вы запустите приложение) и датой, которую мы сохранили при первом запуске приложения.Если пройденных дней больше 14, что означает, что прошло 2 недели, он обновит TextView до новой текущей даты, а также сохранит его снова и перезапишет предыдущую сохраненную дату.

public class MainActivity extends AppCompatActivity {
TextView textView;
DateTime currentDate;
DateTime oldDate;
String currentDateString;
String storedDateString;

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

    //Get a reference to the TextView
    textView = findViewById(R.id.date_TextView);

    // DateTimeFormatter is a Jode-Time class : used for formatting date in this pattern
    DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd.MM.yyyy");

    //Getting current system date  and converting to string using the above pattern
    //DateTIme is also from Joda-Time library
    currentDate = DateTime.now();
    currentDateString = currentDate.toString(dateFormat);

    //Getting stored date string from SharedPreference
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    storedDateString = sharedPreferences.getString("dateInText","null");

    //Checking if stored date is equal to null it means this is the first launch of the app
    if (storedDateString.equals("null"))
    {
        //Storing date using SharedPreference
        SharedPreferences.Editor  editor = sharedPreferences.edit();
        editor.putString("dateInText" , currentDateString);
        storedDateString = currentDateString;
        editor.commit();
    }
    else
    {
        //Converting stored date string into DateTime object
        oldDate = dateFormat.parseDateTime(storedDateString);

        //Calculating difference between stored date and current date
        int daysBetweenBothDates = Days.daysBetween(oldDate,currentDate).getDays();

        //If 2 weeks have been passed then update the stored date
        if(daysBetweenBothDates >= 14) {
            storedDateString = currentDateString;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("dateInText", currentDateString);
            editor.commit();
        }
    }

    //Display stored date
    textView.setText(storedDateString);

  }
}

ПРИМЕЧАНИЕ: Я использую стороннюю библиотеку для всех манипуляций с датой и временем, которая называется Joda-Time .Вам нужно будет включить эту библиотеку, если вы хотите запустить этот код.Вы можете сделать это, перейдя в app \ build.gradle file и добавив implementation 'joda-time:joda-time:2.10.2' в зависимости.Как это

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'joda-time:joda-time:2.10.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...