如何在android xml字符串资源中获取标签

时间:2019-04-08 11:06:26

标签: android xml android-layout android-xml android-xml-attribute

我想在xml数组中获取标记,例如countrycountryCodeiso2iso3

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="country_data">
        <item>
            <country>Afghanistan</country>
            <countryCode>93</countryCode>
            <iso2>AF</iso2>
            <iso3>AFG</iso3>
        </item>
        <item>
            <country>Albania</country>
            <countryCode>355</countryCode>
            <iso2>AL</iso2>
            <iso3>ALB</iso3>
        </item>
        <item>
            <country>Algeria</country>
            <countryCode>213</countryCode>
            <iso2>DZ</iso2>
            <iso3>DZA</iso3>
        </item>
        <item>
            <country>American Samoa</country>
            <countryCode>1-684</countryCode>
            <iso2>AS</iso2>
            <iso3>ASM</iso3>
        </item>
        <item>
            <country>Andorra</country>
            <countryCode>376</countryCode>
            <iso2>AD</iso2>
            <iso3>AND</iso3>
        </item>
        <item>
            <country>Angola</country>
            <countryCode>244</countryCode>
            <iso2>AO</iso2>
            <iso3>AGO</iso3>
        </item>
    </string-array>
</resources>

我想分别将countrycountryCodeiso2iso3放入不同的ArrayLists(ArrayList country,countryCode,iso2,iso3)。 / p>

2 个答案:

答案 0 :(得分:2)

要访问string-array,请执行以下操作:

String[] ar = getResources().getStringhArray(R.array.country_data);

但是,该数组是一维数组。所以,像这样的烤面包

Toast.makeText(this, ar[0], Toast.Length_SHORT).show();

将显示

Afghanistan 93 AF AFG

如果您确定不会在国家/地区名称中插入空格,则可以拆分字符串。

如果xml是外部文件,那么最好使用XmlPullParserFactory来解析文件。在这种情况下,您可以直接访问国家,国家代码,iso2,iso3。

答案 1 :(得分:0)

  

这就是我的方法。

I used XmlPullParserFactory to get the tags from an xml file in the assets folder.

..

XmlPullParser的事件

XMLPullParser的 next()方法将光标指针移动到下一个事件。通常,我们使用XMLPullParser接口中定义的四个常量(作为事件工作)。这些是:

START_TAG:已读取XML起始标签。

TEXT:阅读了文本内容;可以使用getText()方法检索文本内容。

END_TAG:已读取结束标签。

END_DOCUMENT:没有更多可用的事件。

..

Android XMLPullParser XML解析

XMLPullParser将检查具有一系列事件的XML文件,例如上面列出的事件以解析XML文档。

要在Android中使用XMLPullParser读取和解析XML数据,我们需要在Android应用程序中创建XMLPullParserFactory实例,XMLPullParser对象。

下面是我的代码,用于在Android应用程序中使用XMLPullParserFactory,XMLPullParser和一系列事件从XML对象获取所需信息来使用XMLPullParser读取和解析XML数据。

然后将数据传递到BaseAdapter。

package com.f.countryarraytest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    public TextView tvCountryName, tvCountryCode, tvCountryIso2;
    private CustomAdapter customAdapter;
    private static final String tagCountryItem = "country";
    private static final String tagCountryName = "countryName";
    private static final String tagCountryCode = "countryCode";
    private static final String tagCountryIso2 = "countryIso2";
    private static final String tagCountryIso3 = "countryIso3";
    private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
    private ArrayList<HashMap<String, String>> countryListArray;

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

        listView        = findViewById(R.id.listView);

        tvCountryName   = findViewById(R.id.tvMainActivity_CountryName);
        tvCountryCode   = findViewById(R.id.tvMainActivity_CountryCode);
        tvCountryIso2   = findViewById(R.id.tvMainActivity_CountryIso2);

        countryName     = new ArrayList<>();
        countryCode     = new ArrayList<>();
        countryIso2     = new ArrayList<>();
        countryIso3     = new ArrayList<>();

        try{
            countryListArray = new ArrayList<>();
            HashMap<String,String> country = new HashMap<>();

            InputStream inputStream             = getAssets().open("countries.xml");
            XmlPullParserFactory parserFactory  = XmlPullParserFactory.newInstance();
            parserFactory.setNamespaceAware(true);
            XmlPullParser parser                = parserFactory.newPullParser();

            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
            parser.setInput(inputStream,null);

            String tag = "" , text = "";
            int event = parser.getEventType();

            while (event!= XmlPullParser.END_DOCUMENT){
                tag = parser.getName();
                switch (event){
                    case XmlPullParser.START_TAG:
                        if(tag.equals(tagCountryItem))
                            country = new HashMap<>();
                        break;
                    case XmlPullParser.TEXT:
                        text=parser.getText();
                        break;
                    case XmlPullParser.END_TAG:

                        if (tag.equalsIgnoreCase(tagCountryName)){
                            country.put(tagCountryName,text);

                        } else if (tag.equalsIgnoreCase(tagCountryCode)){
                            country.put(tagCountryCode,text);

                        } else if (tag.equalsIgnoreCase(tagCountryIso2)){
                            country.put(tagCountryIso2,text);

                        } else if (tag.equalsIgnoreCase(tagCountryIso3)){
                            country.put(tagCountryIso3,text);

                        } else if (tag.equalsIgnoreCase(tagCountryItem)){

                            if(country != null){
                                countryListArray.add(country);
                            }
                        }

                        /*switch (tag){
                            case tagCountryName: country.put(tagCountryName,text);
                                break;

                            case tagCountryCode: country.put(tagCountryCode,text);
                                break;

                            case tagCountryIso2: country.put(tagCountryIso2,text);
                                break;

                            case tagCountryIso3: country.put(tagCountryIso3,text);
                                break;

                            case tagCountryItem:
                                if(country != null){
                                    countryListArray.add(country);}
                                break;
                        }*/

                        break;
                }
                event = parser.next();
            }

            //Get ArrayList With County Data HashMap
            getHashMapData();

            customAdapter   = new CustomAdapter(this, countryName, countryCode, countryIso2, countryIso3);
            listView.setAdapter(customAdapter);
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }


    }

    private void getHashMapData(){

        countryName.clear();
        countryCode.clear();
        countryIso2.clear();
        countryIso3.clear();

        try {

            if (countryListArray.size() > 0) {

                for (int i = 0; i < countryListArray.size(); i++) {

                    HashMap<String, String> hashmap = countryListArray.get(i);

                    countryName.add(hashmap.get(tagCountryName));
                    countryCode.add(hashmap.get(tagCountryCode));
                    countryIso2.add(hashmap.get(tagCountryIso2));
                    countryIso3.add(hashmap.get(tagCountryIso3));
                }
            }
        } catch (Exception e){}
    }

}
  

这是我的BaseAdapter的代码。

package com.f.countryarraytest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class CustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<String> countryName, countryCode, countryIso2, countryIso3;
    private LayoutInflater layoutInflater;
    private TextView tvSelectedCountryName, tvSelectedCountryCode, tvSelectedCountryIso2;

    public CustomAdapter(MainActivity mainActivity, ArrayList<String> countryName, ArrayList<String> countryCode, ArrayList<String> countryIso2, ArrayList<String> countryIso3){

        this.context        = mainActivity.getApplicationContext();
        this.countryName    = countryName;
        this.countryCode    = countryCode;
        this.countryIso2    = countryIso2;
        this.countryIso3    = countryIso3;
        this.layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        this.tvSelectedCountryName  = mainActivity.tvCountryName;
        this.tvSelectedCountryCode  = mainActivity.tvCountryCode;
        this.tvSelectedCountryIso2  = mainActivity.tvCountryIso2;
    }

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


    @Override
    public Object getItem(int position) {
        return position;
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

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

        if(convertView == null)
        {
            convertView = layoutInflater.inflate(R.layout.custom_listview_country_picker, null);
        }

        LinearLayout llItem;
        final TextView tvCountryName, tvCountryCode, tvCountryIso2;

        llItem          = convertView.findViewById(R.id.llCountryPicker);
        tvCountryName   = convertView.findViewById(R.id.tvCountryName);
        tvCountryCode   = convertView.findViewById(R.id.tvCountryCode);
        tvCountryIso2   = convertView.findViewById(R.id.tvCountryIso2);

        //Set Values
        tvCountryName.setText(countryName.get(position));
        tvCountryCode.setText(String.valueOf(countryCode.get(position)));
        tvCountryIso2.setText(countryIso2.get(position));

        llItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tvSelectedCountryName.setText(tvCountryName.getText().toString().trim());
                tvSelectedCountryCode.setText(tvCountryCode.getText().toString().trim());
                tvSelectedCountryIso2.setText(tvCountryIso2.getText().toString().trim());
            }
        });

        return convertView;
    }
}
  

这是列表项的xml布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="horizontal">

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:id="@+id/llCountryPicker"
    android:gravity="center_vertical"
    android:layout_height="wrap_content">

    <!--Country Flag-->
    <ImageView
        android:layout_width="28dp"
        android:padding="2dp"
        android:contentDescription="countryFlag"
        android:src="@android:drawable/ic_menu_gallery"
        android:id="@+id/ivCountryPicker_CountryFlag"
        android:layout_marginStart="10dp"
        android:layout_height="28dp"
        />

    <!-- Country Code And Name -->
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="5dp"
        android:layout_height="wrap_content">

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

            <TextView
                android:id="@+id/tvCountryIso2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:singleLine="true"
                android:textColorHint="#000"
                android:layout_marginEnd="10dp"
                android:hint="Iso2"
                android:textColor="#000000"
                android:textSize="14dp"
                />
            <TextView
                android:id="@+id/tvCountryName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:textColorHint="#000"
                android:layout_marginEnd="10dp"
                android:hint="country Name"
                android:textColor="#000000"
                android:textSize="14dp"
                />
        </LinearLayout>
        <TextView
            android:id="@+id/tvCountryCode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:singleLine="true"
            android:minEms="3"
            android:textColorHint="#000"
            android:maxEms="5"
            android:layout_marginEnd="10dp"
            android:hint="000"
            android:textColor="#000000"
            android:textSize="14dp"
            />
    </LinearLayout>
</LinearLayout>