在android中的自定义适配器类中添加按钮

时间:2014-06-17 07:20:21

标签: android button custom-adapter

您好,在我的应用程序中,我正在解析json url并显示图像和文本现在我要添加按钮。如果我点击按钮,我想转移到另一个活动。现在我的问题是,如果我点击按钮没有发生任何事情。可以任何人请帮助我。

ListViewAdapter类:

public class ListViewAdapter extends BaseAdapter {

        // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        ImageLoader imageLoader;
        HashMap<String, String> resultp = new HashMap<String, String>();

        public ListViewAdapter(Context context,
                ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
            imageLoader = new ImageLoader(context);
        }

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

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

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

        public View getView(final int position, View convertView, ViewGroup parent) {
            // Declare Variables
            TextView title;

            ImageView thumb_url;


            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View itemView = inflater.inflate(R.layout.listview_item, parent, false);
            // Get the position
            resultp = data.get(position);

            // Locate the TextViews in listview_item.xml
            title = (TextView) itemView.findViewById(R.id.rank);

            // Locate the ImageView in listview_item.xml
            thumb_url = (ImageView) itemView.findViewById(R.id.flag);

            // Capture position and set results to the TextViews
            title.setText(resultp.get(MainActivity.TITLE));

            // Capture position and set results to the ImageView
            // Passes flag images URL into ImageLoader.class
            imageLoader.DisplayImage(resultp.get(MainActivity.THUMB_URL), thumb_url);
            // Capture ListView item click
            Button Add = (Button) itemView.findViewById(R.id.add);
            Add.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // Get the position
                    resultp = data.get(position);
                    Intent intent = new Intent(context, SingleItemView.class);
                    // Pass all data rank
                    intent.putExtra("title", resultp.get(MainActivity.TITLE));
                    // Pass all data country
                    /*intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
                    // Pass all data population
                    intent.putExtra("population",resultp.get(MainActivity.POPULATION));
                    */// Pass all data flag
                    intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
                    // Start SingleItemView Class
                    context.startActivity(intent);

                    Intent in = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(in);
                }

                private void startActivity(Intent in) {
                    // TODO Auto-generated method stub

                }

                private Context getApplicationContext() {
                    // TODO Auto-generated method stub
                    return context;
                }

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            });
            return itemView;
        }

        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

        }
            }

listview_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/flag"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:background="#444"
        android:padding="3dp" />
     <TextView
        android:id="@+id/rank"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"

        android:layout_toRightOf="@+id/flag"
        android:maxLines="1"
        android:textSize="15dip"
        android:textStyle="bold" />


    <!--  <TextView
        android:id="@+id/ranklabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
 -->

  <!--   <ImageView
        android:id="@+id/flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:background="#000000"
        android:layout_toRightOf="@+id/flag"
        android:padding="1dp" />
 -->

     <Button
         android:id="@+id/add"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentRight="true"
         android:layout_below="@+id/rank"
         android:text="Add" />

</RelativeLayout>

MainActivity类:

public class MainActivity extends Activity {
        // Declare Variables
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String TITLE = "title";
        /*static String COUNTRY = "country";
        static String POPULATION = "population";*/
        static String THUMB_URL = "thumb_url";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the view from listview_main.xml
            setContentView(R.layout.listview_main);
            // Execute DownloadJSON AsyncTask
            new DownloadJSON().execute();
        }

        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(MainActivity.this);
                // Set progressdialog title
                mProgressDialog.setTitle("Loading...");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunction
                        .getJSONfromURL("http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php");

                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("veg_food");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("title", jsonobject.getString("title"));
                        /*map.put("country", jsonobject.getString("country"));
                        map.put("population", jsonobject.getString("population"));*/
                        map.put("thumb_url", jsonobject.getString("thumb_url"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) findViewById(R.id.listview);
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(MainActivity.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
}

1 个答案:

答案 0 :(得分:0)

将hashMap存储在视图标记中。

Button Add = (Button) itemView.findViewById(R.id.add);
Add.setTag(resultp);

然后在onClick()中访问它,就像这样

而不是尝试通过可能不引用当前视图的位置访问它,而是通过其标记访问它。在您的代码中,替换

resultp = data.get(position);

resultp = (HashMap<String, String>) view.getTag();

编辑:添加resultp = data.get(position);后,如上所示 用以下

替换onClick()
@Override
public void onClick(View arg0) {
    resultp = (HashMap<String, String>) view.getTag();
    Intent intent = new Intent(context, SingleItemView.class);
    intent.putExtra("title", resultp.get(MainActivity.TITLE));                    
    intent.putExtra("population",resultp.get(MainActivity.POPULATION));
    intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
    context.startActivity(intent);
}