如何使用带有嵌套可点击按钮的自定义列表项创建ListActivity

时间:2011-01-25 19:27:22

标签: android listview listactivity listadapter

现在我有一个活动,显示用户名列表。好的,它有效。但我需要的是显示一个自定义列表视图项目,左侧​​是用户名,右侧是一个按钮(此按钮将调用以编程方式给出的电话号码)。

我知道我必须做一个自定义适配器,但我的技能太低了。而且我也不知道如何使用它。

有人可以帮我制作一个简单的自定义适配器来管理我的listitem,只需一个textview和一个按钮,并为我提供使用该自定义适配器的代码吗?

适配器应该能够使用这个新的list_item2.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">
        <TextView 
        android:id="@+id/friendName"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentLeft="true"
        android:padding="10dp"
        android:textSize="16sp"/>
        <Button
        android:id="@+id/callButton"
        android:layout_alignBaseline="@id/friendName"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Call"
        android:width="100px"
        android:layout_alignParentRight="true"/>
</RelativeLayout> 

这是我现在使用的代码:

list_item.xml:

xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

这是listactivity类:

public class AllActivity extends ListActivity {

    RemoteConnection con; //conexion remota
    //private MyDbAdapter mDbHelper;

    private List<Friend> friends; //lista de amigos
    private List<String> usernames; //lista de usernames de amigos, para rellenar el listview
    //private List<Permission> permissions;

    //para almacenar la config local de mi app, mostrarme o no en el mapa...
    static SharedPreferences settings;
    static SharedPreferences.Editor configEditor;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        settings=PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
        configEditor = settings.edit();

        friends = new ArrayList<Friend>();
        usernames = new ArrayList<String>();

        //mDbHelper=MyApplication.getDatabaseAdapter();
        con = new RemoteConnection();

        actualizar();

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            setResult(1);
            finish();                   
        }
    }
    public void onResume() {
        super.onResume();
        actualizar();       
   }

    public void actualizar()
    {
        //friends = con.RetrieveFriends(settings.getString("login",""));
        friends = MyApplication.getDatabaseAdapter().retrieveAllFriends();
        usernames.clear();

        for (int i=0;i<friends.size();i++)
        //for (int i=0;i<permissions.size();i++)
        {
            usernames.add(i,friends.get(i).getFullName());
            //if (friends.get(i).getLastPosition()!=null)
            //  usernames.add(i,friends.get(i).getLastPosition().getpositiontimeFormated());    
        }
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item3, usernames));
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {


              Bundle bundle = new Bundle(); //bundle is like the letter
              bundle.putString ("user", friends.get(position).getFullName()); //arg1 is the keyword of the txt, arg2 is the txt
              bundle.putString ("email", friends.get(position).getEmail());
              bundle.putString ("permission", friends.get(position).getPermission());

              Intent i=null;
              if (friends.get(position).getPermission().equals("total"))
                  i = new Intent (AllActivity.this, Locate.class);
              else if (friends.get(position).getPermission().equals("perhours"))
                  i = new Intent (AllActivity.this, LocatePerHours.class);
              else
                  i = new Intent (AllActivity.this, LocatePerDays.class);

              i.putExtras(bundle);
              startActivity(i);
              //startActivityForResult(i, 0);
          }
        });
    }

}

1 个答案:

答案 0 :(得分:2)

我编辑了我的代码以与您的代码兼容

我编写代码并进行修改以实现您想要的...我将ListActivity调用InitialActivity并从字符串数组填充列表(填充它们不是您的问题)所以,也许其他的东西会帮助您...

package com.franco.test2;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class InitialActivity extends ListActivity {


//  private List<Friend> friends; //lista de amigos
    private ArrayList<String> usernames; //lista de usernames de amigos, para rellenar el listview
    private String[] usernames_array;
    private ActivityList listAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
        usernames_array = getResources().getStringArray(R.array.usernames);

        actualizar();

    }

    public void actualizar()
    {
        //friends = con.RetrieveFriends(settings.getString("login",""));
//        friends = MyApplication.getDatabaseAdapter().retrieveAllFriends();
//        usernames.clear();

//        for (int i=0;i<usernames.size();i++)
        //for (int i=0;i<permissions.size();i++)
//        {
//            usernames.add(i,friends.get(i).getFullName());
            //if (friends.get(i).getLastPosition()!=null)
            //  usernames.add(i,friends.get(i).getLastPosition().getpositiontimeFormated());    
//        }

        usernames = new ArrayList<String>();
        for(int i = 0 ; i < usernames_array.length ; i++){
            usernames.add(usernames_array[i]);
        }
        listAdapter = new ActivityList(InitialActivity.this, android.R.id.text1, usernames);


//        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item3, usernames));
        setListAdapter(listAdapter);
        ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {



              //startActivityForResult(i, 0);
          }
        });
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
         Bundle bundle = new Bundle(); //bundle is like the letter
         bundle.putString ("user", listAdapter.getItem(position)); //arg1 is the keyword of the txt, arg2 is the txt
//         bundle.putString ("user", friends.get(position).getFullName()); //arg1 is the keyword of the txt, arg2 is the txt
//         bundle.putString ("email", friends.get(position).getEmail());
//         bundle.putString ("permission", friends.get(position).getPermission());

//         Intent i=null;
//         if (friends.get(position).getPermission().equals("total"))
//             i = new Intent (AllActivity.this, Locate.class);
//         else if (friends.get(position).getPermission().equals("perhours"))
//             i = new Intent (AllActivity.this, LocatePerHours.class);
//         else
//             i = new Intent (AllActivity.this, LocatePerDays.class);
//
//         i.putExtras(bundle);
//         startActivity(i);
    }

    private OnClickListener callBtnListener = new OnClickListener(){

        public void onClick(View v) {
            Log.i("Info","Username: " + v.getTag());
        }};

    class ActivityList extends ArrayAdapter<String>{

        public ActivityList(Context context, int textViewResourceId, ArrayList<String> objects) {
            super(context, textViewResourceId, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView == null){
                LayoutInflater inflater = LayoutInflater.from(InitialActivity.this);
                convertView = inflater.inflate(R.layout.new_list_item2, parent, false);
                holder = new ViewHolder();

                holder.text = (TextView)convertView.findViewById(R.id.friendName);
                holder.button = (Button)convertView.findViewById(R.id.callButton);

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(getItem(position));
            holder.button.setOnClickListener(callBtnListener);
            holder.button.setTag( getItem(position) );
            return convertView;
        }

    }

    static class ViewHolder{
        TextView text;
        Button button;
    }

}

我还删除了最后一行(onClick)并在列表活动中添加了onClickListener。

<?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="wrap_content">
        <TextView 
            android:id="@+id/friendName"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:layout_alignParentLeft="true"
            android:padding="10dp"
            android:textSize="16sp"/>
        <Button
            android:id="@+id/callButton"
            android:layout_alignBaseline="@id/friendName"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="Call"
            android:width="100px"
            android:layout_alignParentRight="true"/>
</RelativeLayout>

我在我的设备中测试并且工作,我删除了DataHolder类。

Bundle map,Intent等其他内容被评论,因为我认为不是你的问题。

欢呼声。