将不同(png)图标分配给类别中的不同项目

时间:2017-09-16 10:14:05

标签: android

我知道有些人已经问过这个问题,但我找不到我想要的答案。如果有人可以提供帮助,将会感激不尽。

这个想法:当我点击editText时,我想要一个listpopupWindow“下拉”,用不同的类别来选择。这部分我想我可以管理。我无法管理的部分是为每个项目添加图标。

我有一个字符串数组,命名类别包含不同的项目。 我如何在我的片段类中调用它:

<?php
/*
  Template Name: failed
 */
get_header();

?>

<div class="container">

    <div class="row">
        <div class="col-md-12">
            <p>Payment Cancelled </p>
            <?php
            global $wpdb;

            $today = date('Y-m-d');
            $type = "Perfect Money";

            $table_name = $wpdb->prefix . "payError";
            $wpdb->insert( $table_name, array(
            'date' => $today,
            'type' => $type
            ));
            ?> 
        </div>
    </div>  
</div>
<?php get_footer(); ?>

我有一个图标:

final String[] categories = getResources().getStringArray(R.array.categories);

(我正在使用API​​ 15,这就是为什么它说“ResourcesCompat ...”)

我尝试以不同的方式解决它,每次我尝试使用像setIcon这样的东西,但它没有用。在Drawable中,我将其更改为

  Drawable drawable_business = ResourcesCompat.getDrawable(getResources(),R.drawable.business,null);

有一个setImageIcon,但作为一个参数,必须有一个Icon?我不明白,请有人帮忙..

此链接是我编写代码时所遵循的链接 http://www.informit.com/articles/article.aspx?p=2078060&seqNum=4

2 个答案:

答案 0 :(得分:0)

您可以扩展ArrayAdapter并实现getView(),如下所示:

公共类CustomAdapter扩展了ArrayAdapter {

public CustomAdapter(Context context, int resource,String[] strings) {
    super(context, resource, strings);//the resource should be defined yourself
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    ImageView imageView = convertView.findViewById(R.id.img);
    imageView.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_launcher));
    return convertView;
}

}

如果我明白了。

答案 1 :(得分:0)

// use the Custom Autocomplete Text View to set Text and Image in dropdown

// MainActivity.Java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;

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

public class MainActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
            "India",
            "Pakistan",
            "Sri Lanka",
            "China",
            "Bangladesh",
            "Nepal",
            "Afghanistan",
            "North Korea",
            "South Korea",
            "Japan"
    };

 // Array of integers points to images stored in /res/drawable-ldpi/
    int[] flags = new int[]{
                R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher,
         R.mipmap.ic_launcher
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };




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


        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
                HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", countries[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            hm.put("cur", currency[i]);
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt"};

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.autocomplete_layout, from, to);

        // Getting a reference to CustomAutoCompleteTextView of activity_main.xml layout file
        CustomAutoCompleteTextView autoComplete = ( CustomAutoCompleteTextView) findViewById(R.id.autocomplete);


        /** Defining an itemclick event listener for the autocompletetextview */
        OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                /** Each item in the adapter is a HashMap object. 
                 *  So this statement creates the currently clicked hashmap object
                 * */
                HashMap<String, String> hm = (HashMap<String, String>) arg0.getAdapter().getItem(position);

                /** Getting a reference to the TextView of the layout file activity_main to set Currency */
                TextView tvCurrency = (TextView) findViewById(R.id.tv_currency) ;

                /** Getting currency from the HashMap and setting it to the textview */
                tvCurrency.setText("Currency : " + hm.get("cur"));
            }
        };

        /** Setting the itemclick event listener */
        autoComplete.setOnItemClickListener(itemClickListener);

        /** Setting the adapter to the listView */
        autoComplete.setAdapter(adapter);        

    }

    /** A callback method, which is executed when this activity is about to be killed
     * This is used to save the current state of the activity 
     * ( eg :  Configuration changes : portrait -> landscape )  
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        TextView tvCurrency = (TextView) findViewById(R.id.tv_currency) ;       
        outState.putString("currency", tvCurrency.getText().toString());
        super.onSaveInstanceState(outState);
    }

    /** A callback method, which is executed when the activity is recreated 
     * ( eg :  Configuration changes : portrait -> landscape )  
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        TextView tvCurrency = (TextView) findViewById(R.id.tv_currency) ;       
        tvCurrency.setText(savedInstanceState.getString("currency"));
        super.onRestoreInstanceState(savedInstanceState);
    }
}



/// CustomAutoCompleteTextView.java
import android.content.Context;
import android.util.AttributeSet;

import java.util.HashMap;

/** Customizing AutoCompleteTextView to return Country Name   
 *  corresponding to the selected item
 */
public class CustomAutoCompleteTextView extends android.support.v7.widget.AppCompatAutoCompleteTextView {

    public CustomAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /** Returns the country name corresponding to the selected item */
    @Override
    protected CharSequence convertSelectionToString(Object selectedItem) {
        /** Each item in the autocompetetextview suggestion list is a hashmap object */
        HashMap<String, String> hm = (HashMap<String, String>) selectedItem;
        return hm.get("txt");
    }
}

//// activity_main.xml
<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" >

    <com.demo.constraintlayout.CustomAutoCompleteTextView
        android:id="@+id/autocomplete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textColor="@android:color/black"
        android:hint="@string/str_hnt_autocomplete"
        android:completionThreshold="1"

        />

    <TextView 
        android:id="@+id/tv_currency"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"        
        android:layout_below="@id/autocomplete"
        />

</RelativeLayout>


///autocomplete_layout.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:orientation="horizontal"    
     >

    <ImageView 
            android:id="@+id/flag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/hello_world"
            android:padding="10dp"
    />

    <TextView 
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15dp" 
            android:padding="10dp"          
    />  

</LinearLayout>