点击Android Java动态按钮

时间:2016-11-20 20:18:06

标签: java android json xml adapter

我从我从JSON对象/数组中获取的数据生成按钮。从API获取。 目前我有20个循环可以说(20个数据,20个按钮)。

按钮的xml /布局如下所示:

    <Button
        android:id="@+id/details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

目前获取数据并在我的布局中打印的代码如下所示:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://192.168.178.32:8888/test/public/index";
       ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<>();

        new GetContacts().execute();
    lv = (ListView) findViewById(R.id.list);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

    @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 {
                // Getting JSON Array node
                JSONArray jsonArray = new JSONArray(jsonStr);

                // looping through All Contacts
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject c = jsonArray.getJSONObject(i);

                    String id = c.getString("id");
                    String name = c.getString("name");
                    String description = c.getString("description");

                    // tmp hash map for single contact
                    HashMap<String, String> data = new HashMap<>();

                    // adding each child node to HashMap key => value
                    data.put("id", id);
                    data.put("name", name);
                    data.put("description", description);

                    // adding contact to contact list
                    contactList.add(data);
                }
            } 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(
                MainActivity.this, contactList,
                R.layout.list_item, new String[]{"name", "description"}, new int[]{R.id.name,
                R.id.description, R.id.release_at});

        lv.setAdapter(adapter);
    }

我的适配器看起来像这样:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<String> friends;
    private Activity activity;

    public RecyclerAdapter(Activity activity, List<String> friends, ArrayList<HashMap<String, String>> contactList) {
        this.friends = friends;
        this.activity = activity;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        //inflate your layout and pass it to view holder
        LayoutInflater inflater = activity.getLayoutInflater();
        View view = inflater.inflate(android.R.layout.simple_list_item_1, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder viewHolder, int position) {

        viewHolder.item.setText(friends.get(position));
    }

    @Override
    public int getItemCount() {
        return (null != friends ? friends.size() : 0);
    }

    /**
     * View holder to display each RecylerView item
     */
    protected class ViewHolder extends RecyclerView.ViewHolder {
        private TextView item;

        public ViewHolder(View view) {
            super(view);
            item = (TextView) view.findViewById(android.R.id.text1);
        }
    }

}

我的想法是点击每个按钮,并在另一个活动中显示更详细的相关数据。

但是我怎样才能运行循环并获得正确的按钮(id)并使用其相关数据创建一个新的Activity。

2 个答案:

答案 0 :(得分:0)

在适配器的getView方法中,您可以将onClickLister设置为该行中的按钮,该按钮将引用该行的数据。使用意图开始详细活动,并将点击的项目数据作为额外内容添加。

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

    //Inflate your row

    button.setOnClickListener(new OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
             HashMap<String, String> item = contactsList.get(position);
             //Create the intent to start another activity
             Intent intent = new Intent(view.getContext(), DetailActivity.class);
             intent.putExtra("data", item);
             view.getContext().startActivity(intent);
        }
    });
});

在接收活动中,您可以从意图中获取数据:

HashMap<String, String> data = getIntent().getExtras().getParcelableExtra("data");

答案 1 :(得分:0)

扩展ArrayAdapter并将构造函数参数中的联系人列表传递给它。将该列表分配到ArrayAdapter内的字段,然后在getView()方法中,您可以通过简单list.get(position)获取商品。