无论如何我可以将我的代码更改为android视图中的图标的再循环视图吗?

时间:2017-01-10 06:33:15

标签: android android-recyclerview

我有一个活动,其中的项目来自数据库,我想要设置相同的图标。我尝试了listview,但听说了recyclerview,但我似乎无法找到解决方法,我该如何加载它。请帮助

这是我的列表视图:

public class TypeMenu extends AppCompatActivity {

    private String TAG = TypeMenu.class.getSimpleName();
    String bid;

    private ProgressDialog pDialog;
    private ListView lv;
    private static final String TAG_BID = "bid";

    // URL to get contacts JSON
    private static String url = "http://cloud....com/brtemp/index.php";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_type_menu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();


        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // getting values from selected ListItem

                HashMap<String, String> selected = contactList.get(position);
                String selectedId= selected.get("id");
                Intent in = new Intent(getApplicationContext(), SubMenu.class);
                //  sending pid to next activity
                in.putExtra("id",selectedId);
                startActivityForResult(in, 100);
                Toast.makeText(getApplicationContext(),"Toast" +selectedId ,Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(TypeMenu.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
           // Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
         String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);





            if (jsonStr != null) {
                try {
                    JSONArray jsonArry = new JSONArray(jsonStr);

                    for (int i = 0; i < jsonArry.length(); i++)
                    {

                        JSONObject c = jsonArry.getJSONObject(i);
                        String id = c.getString("id");
                        String type = c.getString("type");
                        HashMap<String, String> contact = new HashMap<>();

                       contact.put("id", id);
                        contact.put("type", type);
                        contactList.add(contact);


                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    TypeMenu.this, contactList,
                    R.layout.list_item, new String[]{ "type","id"},
                    new int[]{
                    R.id.type});

            lv.setAdapter(adapter);
        }

}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
        }

这是我的list_item.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"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="15dp"
            />

        <TextView
            android:id="@+id/type"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp"
            />
    </LinearLayout>


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



        <ImageView
            android:id="@+id/arrow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="10dp"
            android:paddingRight="10dp"
            android:paddingBottom="10dp"
            />
</LinearLayout>
    </LinearLayout>

2 个答案:

答案 0 :(得分:1)

试试这个:

这里是lsit_item.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">

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

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

        <TextView
            android:id="@+id/type"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10dp" />
    </LinearLayout>

    <ImageView
        android:id="@+id/arrow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp"/>
</LinearLayout>

在您的活动中初始化此内容;

 int[] images = new int[]{
    R.drawable.dropdown,
};

// Keys used in Hashmap
    String[] from = { "image","id","type" };

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

doInbanckground

for (int i = 0; i < jsonArry.length(); i++)
  {
JSONObject c = jsonArry.getJSONObject(i);
       String id = c.getString("id");
       String type = c.getString("type");
       HashMap<String, String> contact = new HashMap<>();
       contact.put("id", id);
       contact.put("type", type);
       contact.put("image", Integer.toString(images[0]) );
       contactList.add(contact);

       }

同时在onPostExecute替换上面的代码中添加此内容:

   ListAdapter adapter = new SimpleAdapter(
                TypeMenu.this, contactList,
                R.layout.list_item, from,to);

        lv.setAdapter(adapter);

答案 1 :(得分:0)

您需要创建自定义RecylerView adapter

第1步:gradle

dependencies {
    ...
    compile "com.android.support:recyclerview-v7:23.0.1"
}

第2步:layout/activity_name.xml

<android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

第3步:创建自定义适配器

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
            private ArrayList<String> mDataset;

            // Provide a reference to the views for each data item
            // Complex data items may need more than one view per item, and
            // you provide access to all the views for a data item in a view holder
            public class ViewHolder extends RecyclerView.ViewHolder {
                    // each data item is just a string in this case
                    public TextView txtHeader;
                    public TextView txtFooter;

                    public ViewHolder(View v) {
                            super(v);
                            txtHeader = (TextView) v.findViewById(R.id.firstLine);
                            txtFooter = (TextView) v.findViewById(R.id.secondLine);
                    }
            }

   public MyAdapter(ArrayList<String> myDataset) {
                    mDataset = myDataset;
            }

            // Create new views (invoked by the layout manager)
            @Override
            public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                            int viewType) {
                    // create a new view
                    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
                    // set the view's size, margins, paddings and layout parameters
                    ViewHolder vh = new ViewHolder(v);
                    return vh;
            }

            // Replace the contents of a view (invoked by the layout manager)
            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
                    // - get element from your dataset at this position
                    // - replace the contents of the view with that element
                    final String name = mDataset.get(position);
                    holder.txtHeader.setText(mDataset.get(position));
                    holder.txtHeader.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                    remove(name);
                            }
                        });

                    holder.txtFooter.setText("Footer: " + mDataset.get(position));

            }

            // Return the size of your dataset (invoked by the layout manager)
            @Override
            public int getItemCount() {
                    return mDataset.size();
            }

    }

第4步:在activity.java

setContentView(R.layout.my_activity);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(myDataset);
        mRecyclerView.setAdapter(mAdapter);