带有可点击按钮的Android列表视图

时间:2015-10-13 13:30:34

标签: android listview adapter

大家好我通过本教程实现了一个带有可点击按钮的列表视图 - > https://www.youtube.com/watch?v=ZEEYYvVwJGY 我希望实现相同的输出。 但是我有一个小问题,因为我的列表视图是从mysql数据库填充但是教程没有从mysql数据库中填充,所以我们有一个不同的适配器。

教程中的代码

public class MainActivity extends AppCompatActivity{

private ArrayList<String> data = new ArrayList<String>();

@Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance);
        ListView lv = (ListView) findViewById(R.id.listview);
        lv.setAdapter(new MyListAdapter(this, R.layout.list_item, data));
}

} 

然后我们假设这是教程MyListAdapter

private class MyListAdapter extends ArrayAdapter<String>{
    private int layout;
    public MyListAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
        layout = resource;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder mainViewHolder = null;
        if (convertView == null){
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(layout, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
            viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
            viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
            viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
            viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
                }
            });
            convertView.setTag(viewHolder);
        }
        return convertView;
    }
}

我的问题在于这一部分 setAdapter

 mylistView = (ListView) findViewById(R.id.list);
                final ListAdapter adapter = new SimpleAdapter(Attendance.this,
                        studentList, R.layout.list_att, new String[]{
                        TAG_ID, TAG_NAME}, new int[]{
                       R.id.studId, R.id.studName});
                mylistView.setAdapter(adapter);

我该怎么办?任何帮助将不胜感激提前感谢:)

这是我的代码

public class Attendance extends AppCompatActivity {
    TextView Date;;
    ListView mylistView;
    private ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
    TextView Name;

    private static String url = "http://10.0.2.2/MobileClassRecord/getStudent.php";

    private static final  String TAG_STUDENTS = "students";
    private static final  String TAG_ID = "stud_id";
    private static final  String TAG_NAME = "stud_name";

    JSONArray students = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendance);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Date = (TextView) findViewById(R.id.tvDate);
        final Calendar calendar = Calendar.getInstance();
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        int mm = calendar.get(Calendar.MONTH);
        int yy = calendar.get(Calendar.YEAR);

        Date.setText(new StringBuilder().append(yy).append("-").append(mm + 1).append("-").append(dd));

        new JSONParse().execute();

        studentList = new ArrayList<HashMap<String, String>>();
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject>{
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            Name =(TextView) findViewById(R.id.studName);
            pDialog = new ProgressDialog(Attendance.this);
            pDialog.setMessage("Getting Data from Database...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected JSONObject doInBackground(String... params) {
            JSONParser jParser = new JSONParser();

            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            pDialog.dismiss();
            try {
                students = jsonObject.getJSONArray(TAG_STUDENTS);
                for (int i = 0; i < students.length(); i++){
                    JSONObject c =students.getJSONObject(i);

                    final String Id = c.getString(TAG_ID);
                    String Name = c.getString(TAG_NAME);

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_ID, Id);
                    map.put(TAG_NAME, Name);

                    studentList.add(map);
                    mylistView = (ListView) findViewById(R.id.list);
                    final ListAdapter adapter = new SimpleAdapter(Attendance.this,
                            studentList, R.layout.list_att, new String[]{
                            TAG_ID, TAG_NAME}, new int[]{
                           R.id.studId, R.id.studName});
                    mylistView.setAdapter(adapter);
                    mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            String ID = ((TextView) (view.findViewById(R.id.studId))).getText().toString();
                            Toast.makeText(Attendance.this, "List Clicked " + ID, Toast.LENGTH_LONG).show();
                            SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
                            preferences.edit().putString("id", ID).commit();
                        }
                    });

                }
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }

    private class MyListAdapter extends ArrayAdapter<String>{
        private int layout;
        public MyListAdapter(Context context, int resource, List<String> objects) {
            super(context, resource, objects);
            layout = resource;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder mainViewHolder = null;
            if (convertView == null){
                LayoutInflater inflater = LayoutInflater.from(getContext());
                convertView = inflater.inflate(layout, parent, false);
                ViewHolder viewHolder = new ViewHolder();
                viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
                viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
                viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
                viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
                viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
                    }
                });
                convertView.setTag(viewHolder);
            }
            mainViewHolder = (ViewHolder) convertView.getTag();
            mainViewHolder.tvid.setText(getItem(position));
            return convertView;
        }
    }

    public class ViewHolder{
        TextView tvid, tvname;
        Button btnP, btnA;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_attendance, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                Intent intent = new Intent(Attendance.this, SpecificClassRecord.class);
                startActivity(intent);
                return true;
            case R.id.action_view_attendance:
                Intent intent1 = new Intent(Attendance.this, ViewAttendance.class);
                startActivity(intent1);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Sample Layout

1 个答案:

答案 0 :(得分:0)

像Udi说的那样,更多信息会很好。

代码中的一个奇怪之处在于getView()方法。

你有

if(convertView==null){
  ...
}else{
...
}

我认为其他部分是错误的。只需删除else和括号(不是它的代码洞察力)。 else部分中的代码很重要,因为没有它,代码在第一次加载View时不会更改TextView。这意味着,你的getView将什么都不做

修改

作者更改了代码。你现在有两个不同的适配器......

在我看来,getView()方法看起来应该是这样的

public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder mainViewHolder = null;
    if (convertView == null){
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(layout, parent, false);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
        viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
        viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
        viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
        viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
            }
        });
        convertView.setTag(viewHolder);
    }
    mainViewHolder = (ViewHolder) convertView.getTag();
    mainViewHolder.tvid.setText(getItem(position));
    return convertView;
}
}

但对我来说,目前尚不清楚问题究竟在哪里。应用程序崩溃还是仅仅是您不理解的行为?如果是,究竟是什么? 如果应用程序崩溃,究竟是什么时候?

编辑2:

mylistView = (ListView) findViewById(R.id.list);
            final ListAdapter adapter = new MyListAdapter(Attendance.this,
                     R.layout.list_att, new String[]{
                    TAG_ID, TAG_NAME});
            mylistView.setAdapter(adapter);

也许这就是全部。我假设你的行的布局是由layoutressource R.layout.list_att给出的,而TAG_ID和TAG_Name是在之前的某个地方定义的。

我看到你的新适配器需要一个字符串列表。在设置适配器

之前插入以下内容
List<String> test = new ArrayList<String>();
test.add("1");
test.add("2"):
test.add("3");

然后你的适配器应该是这样的

final ListAdapter adapter = new MyListAdapter(Attendance.this,
                     R.layout.list_att, test);