парсинг двух разных XML-файлов одновременно в listview android - PullRequest
2 голосов
/ 06 марта 2019

Я работаю над XML в моем проекте Android и я новичок.у меня есть один и тот же XML на другом языке тоже, как этот

<sura index="1" name="الفاتحة">
    <aya index="1" text="الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ" bismillah="بِسْمِ اللَّهِ الرَّحْمَنِ 
    الرَّحِيمِ" />
    <aya index="2" text="الرَّحْمَنِ الرَّحِيمِ" />
    <aya index="3" text="مَالِكِ يَوْمِ الدِّينِ" />
    <aya index="4" text="إِيَّاكَ نَعْبُدُ وَإِيَّاكَ نَسْتَعِينُ" />
    <aya index="5" text="اهْدِنَا الصِّرَاطَ الْمُسْتَقِيمَ" />
    <aya index="6" text="صِرَاطَ الَّذِينَ أَنْعَمْتَ عَلَيْهِمْ غَيْرِ الْمَغْضُوبِ عَلَيْهِمْ وَلَا الضَّالِّينَ" />
</sura>

этот на арабском

<sura index="1" name="الفاتحة">
    <aya index="1" text="In the name of Allah, most benevolent, ever-merciful."/>
    <aya index="2" text="ALL PRAISE BE to Allah, Lord of all the worlds,"/>
    <aya index="3" text="Most beneficent, ever-merciful,"/>
    <aya index="4" text="King of the Day of Judgement."/>
    <aya index="5" text="You alone we worship, and to You alone turn for help."/>
    <aya index="6" text="Guide us (O Lord) to the path that is straight,"/>
    <aya index="7" text="The path of those You have blessed, Not of those who have earned Your anger, nor those who have gone astray."/>
</sura>

этот на английском.

Я успешно сделал анализдля ая на арабском языке, используя этот код

private List<String> getAllAyaFromSuraIndex(String suraIndex) throws XmlPullParserException, IOException {
     list = new ArrayList<>();

    XmlPullParser parser = getResources().getXml(R.xml.quran_arabic);
    while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
        if (parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("sura")) {
            String index = parser.getAttributeValue(0);

            // Match given sure index
            if (index.equals(suraIndex)) {
                // Move to first aya tag inside matched sura index
                parser.next();

                // This loop will exit when it reaches sura end tag </sura>
                while (parser.getName().equals("aya")) {
                    if (parser.getEventType() == XmlPullParser.START_TAG) {
                        list.add(parser.getAttributeValue(null,"index") + ".\n" + parser.getAttributeValue(null,"text"));
                    }

                    // Move to next aya tag
                    parser.next();
                }

                break;
            }
        }

        parser.next();
    }

    return list;
}

У меня есть просмотр списка с двумя текстовыми представлениями, один для арабского и один для английского.Я перепробовал все, но не получил результатов.

1 Ответ

2 голосов
/ 06 марта 2019

Когда вы разрабатываете многоязычное приложение, лучший способ обработать переводы в Android - это определить контент в категории локали. Позвольте мне объяснить это вам

1-й шаг создать каталог с указанными именами локалей values- (language) например, values-ar

MyProject/
          res/
              values-es/
                        strings.xml
              values-ar/
                        strings.xml

Значения-эс / strings.xml

 <resources>
     <string name="ayah1">ALL PRAISE BE to Allah, Lord of all the worlds,.</string>
     <string name="ayah2">Most beneficent, ever-merciful,</string>
 </resources>

значения ар / strings.xml

 <resources>
     <string name="ayah1">الْحَمْدُ لِلَّهِ رَبِّ الْعَالَمِينَ</string>
     <string name="ayah2">الرَّحْمَنِ الرَّحِيمِ</string>
 </resources>

2-й шаг теперь используйте эти строки в ваших файлах просмотра как

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.javapapers.multilingualapp.MainActivity">

    <TextView
        android:id="@+id/string"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ayah1"                 //here the values being used
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />



</android.support.constraint.ConstraintLayout>

3-й и последний шаг теперь, когда вы хотите изменить язык, просто измените локаль, используя следующую функцию

public void setLocale(String localeName) {
        if (!localeName.equals(currentLanguage)) {
            myLocale = new Locale(localeName);
            Resources res = getResources();
            DisplayMetrics dm = res.getDisplayMetrics();
            Configuration conf = res.getConfiguration();
            conf.locale = myLocale;
            res.updateConfiguration(conf, dm);
            Intent refresh = new Intent(this, MainActivity.class);
            refresh.putExtra(currentLang, localeName);
            startActivity(refresh);
        } else {
            Toast.makeText(MainActivity.this, "Language already selected!", Toast.LENGTH_SHORT).show();
        }
    }
...