Android如何在不扩展listActivity的情况下使用listView的适配器

发布于 2024-12-17 20:31:36 字数 994 浏览 3 评论 0原文

我有一个带有选项卡的应用程序。在一个选项卡中,我需要将数据(字符串)放入行中。为此,我选择了 tableLayout,但当我想在其行上使用 contextmenu 时,它不起作用。

我可以显示 contextmenu onLongClick 但问题是我无法获取有关所选行的信息来编辑或删除所选行。然后我在讨论中读到,如果我们有很多行,则使用 listViewtablelayout 更好。但是我看到的示例扩展了 listactivity 但我不想这样做。

因此,当我尝试在不扩展 listactivity 的情况下处理 listView 时,我不知道该怎么做,我的意思是我从未使用过 listView code> 之前,所以我尝试在互联网上找到的不同示例来理解它,但它不起作用。这是我到目前为止对 listView 所做的事情:

String [] items=getRessources().getStringArray(R.arra.resolution);
 //Resolution is an array of strings
ListView lv=(ListeView) findViewById(R.id.listView);
v.setAdapter(new ArrayAdapter<string>(this, android.R.layout.simple_list_item_1, items);

当我编译它时,我得到一个包含数组元素的列表,但首先,我想更改文本的颜色,但我不能。其次,我想将行动态添加到列表中,但我也不知道该怎么做。我想我必须使用适配器来做到这一点,但我不知道如何做。 有人可以指导我完成这个吗?我只想知道如何将我的列表附加到适配器,该适配器允许我动态添加行、添加 contextMenu 等。

I have an application with tabs. In one tab I need to put data (strings) in rows. To do so I chose tableLayout but when I wanted to use a contextmenu on its rows it doesn't work.

I can show the contextmenu onLongClick but the problem is that I can't get the info about the selected row to edit or delete the selected row. Then I read in a discussion that using listView is better than tablelayout if we have many rows. But the examples I saw extend listactivity but I don't want to do this.

So when I try working on a listView without extending listactivity I don't know how to do it what I mean is that I've never used listView before so I try different examples I found on the internet to understand it but it's not working. Here's what I did so far for the listView:

String [] items=getRessources().getStringArray(R.arra.resolution);
 //Resolution is an array of strings
ListView lv=(ListeView) findViewById(R.id.listView);
v.setAdapter(new ArrayAdapter<string>(this, android.R.layout.simple_list_item_1, items);

When I compile it I get a list with elements of my array in it but first, I want to change the color of text which I can't. And secondly I want to add rows dynamically to the list which I don't know how to do either. I think I have to use an adapter to do it but I don't know how.
Can someone please guide me through this. I just want to know how to attach my list to an adapter which'll allow me to dynamically add rows, add contextMenu etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

终难愈 2024-12-24 20:31:36

主 Activity 类:

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class SelectedActivity extends Activity {

private SelectedAdapter selectedAdapter;
private ArrayList<String> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selected_example);

    // populate the model - a simple a list
    list = new ArrayList<String>();
    list.add("Apple");
    list.add("Orange");
    list.add("Grape");
    list.add("Grape1");
    list.add("Grape2");
    list.add("Grape3");
    list.add("Grape4");
    list.add("Grape5");
    list.add("Grape6");

    // create our SelectedAdapter
    selectedAdapter = new SelectedAdapter(this,0,list);
    selectedAdapter.setNotifyOnChange(true);

    ListView listview = (ListView) findViewById(R.id.listExample);
    listview.setAdapter(selectedAdapter);

    listview.setOnItemClickListener(new OnItemClickListener() {
        //@Override
        public void onItemClick(AdapterView arg0, View view,
                                       int position, long id) {
            // user clicked a list item, make it "selected"
            selectedAdapter.setSelectedPosition(position);
        }
    });
}

适配器类:

   import java.util.List;
    import android.content.Context;
    import android.graphics.Color;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.TextView;

    public class SelectedAdapter extends ArrayAdapter{

        // used to keep selected position in ListView
        private int selectedPos = -1;   // init value for not-selected

        public SelectedAdapter(Context context, int textViewResourceId,
                       List objects) {
             super(context, textViewResourceId, objects);
        }
        public void setSelectedPosition(int pos){
        selectedPos = pos;
             // inform the view of this change
             notifyDataSetChanged();
        }
        public int getSelectedPosition(){
             return selectedPos;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                 View v = convertView;
                 // only inflate the view if it's null
                 // if (v == null) {
                        LayoutInflater vi =   (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.selected_row, null);
                 //  }

                 // get text view
                     TextView label = (TextView)v.findViewById(R.id.txtExample);
                     Button btn=(Button)v.findViewById(R.id.btn1);

                     // change the row color based on selected state
                     if(selectedPos == position){
                        label.setBackgroundColor(Color.CYAN);
                        btn.setBackgroundResource(R.drawable.next);
                     }
                     else{
                        label.setBackgroundColor(Color.WHITE);
                     }

                     label.setText(this.getItem(position).toString());       
                     return(v);
        }
}

main Activity class:

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class SelectedActivity extends Activity {

private SelectedAdapter selectedAdapter;
private ArrayList<String> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.selected_example);

    // populate the model - a simple a list
    list = new ArrayList<String>();
    list.add("Apple");
    list.add("Orange");
    list.add("Grape");
    list.add("Grape1");
    list.add("Grape2");
    list.add("Grape3");
    list.add("Grape4");
    list.add("Grape5");
    list.add("Grape6");

    // create our SelectedAdapter
    selectedAdapter = new SelectedAdapter(this,0,list);
    selectedAdapter.setNotifyOnChange(true);

    ListView listview = (ListView) findViewById(R.id.listExample);
    listview.setAdapter(selectedAdapter);

    listview.setOnItemClickListener(new OnItemClickListener() {
        //@Override
        public void onItemClick(AdapterView arg0, View view,
                                       int position, long id) {
            // user clicked a list item, make it "selected"
            selectedAdapter.setSelectedPosition(position);
        }
    });
}

Adapter class:

   import java.util.List;
    import android.content.Context;
    import android.graphics.Color;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.TextView;

    public class SelectedAdapter extends ArrayAdapter{

        // used to keep selected position in ListView
        private int selectedPos = -1;   // init value for not-selected

        public SelectedAdapter(Context context, int textViewResourceId,
                       List objects) {
             super(context, textViewResourceId, objects);
        }
        public void setSelectedPosition(int pos){
        selectedPos = pos;
             // inform the view of this change
             notifyDataSetChanged();
        }
        public int getSelectedPosition(){
             return selectedPos;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                 View v = convertView;
                 // only inflate the view if it's null
                 // if (v == null) {
                        LayoutInflater vi =   (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.selected_row, null);
                 //  }

                 // get text view
                     TextView label = (TextView)v.findViewById(R.id.txtExample);
                     Button btn=(Button)v.findViewById(R.id.btn1);

                     // change the row color based on selected state
                     if(selectedPos == position){
                        label.setBackgroundColor(Color.CYAN);
                        btn.setBackgroundResource(R.drawable.next);
                     }
                     else{
                        label.setBackgroundColor(Color.WHITE);
                     }

                     label.setText(this.getItem(position).toString());       
                     return(v);
        }
}
打小就很酷 2024-12-24 20:31:36

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg8"
    android:id="@+id/RootView"
    >
        <LinearLayout android:id="@+id/myLayout"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent">
       </LinearLayout>

</LinearLayout>

您需要定义一个 xml,用于保存每行的数据:

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

   <TableRow
       android:id="@+id/tableRow1"
       android:layout_width="793dp"
       android:layout_height="wrap_content"
       android:layout_weight="0.23" >

        <TextView android:id="@+id/col1"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:width="50dp"
           android:textSize="18sp"

        />
        <TextView android:id="@+id/col2"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:width="150dp"
            android:textSize="18sp"
        />
      <ImageView android:id="@+id/editimage"
            android:background="@drawable/edit"
            android:clickable="true"
            android:onClick="ClickHandlerForEditImage" 
            android:layout_width="35dp" 
         android:layout_height="35dp"/>  

    </TableRow>

</LinearLayout>

在上面的 xml 中,我还包含了 ImageView,它并不是真正必需的,但这只是为了更新您,我们可以包含其他内容控制也。

&最后你的相关类中应该有一个函数:

private void LoadData()
{

    DBAdapter db = new DBAdapter(this);
    db.open();
    Cursor cur = db.GetData();
    private ListView lv = (ListView)findViewById(R.id.myLayout);
    lv.setAdapter(null);
    if(cur.moveToFirst())
    {
            String[] from = new String[] {"_id","column1"};
            int[] to = new int[] {R.id.col1, R.id.col2};
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.grid_item, cur, from, to);
            lv.setAdapter(adapter);  

     }
       db.close();
         }
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg8"
    android:id="@+id/RootView"
    >
        <LinearLayout android:id="@+id/myLayout"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent">
       </LinearLayout>

</LinearLayout>

You need to define an xml which will be used to hold data of each row:

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

   <TableRow
       android:id="@+id/tableRow1"
       android:layout_width="793dp"
       android:layout_height="wrap_content"
       android:layout_weight="0.23" >

        <TextView android:id="@+id/col1"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:width="50dp"
           android:textSize="18sp"

        />
        <TextView android:id="@+id/col2"
            android:layout_height="fill_parent"
            android:layout_width="wrap_content"
            android:width="150dp"
            android:textSize="18sp"
        />
      <ImageView android:id="@+id/editimage"
            android:background="@drawable/edit"
            android:clickable="true"
            android:onClick="ClickHandlerForEditImage" 
            android:layout_width="35dp" 
         android:layout_height="35dp"/>  

    </TableRow>

</LinearLayout>

In the above xml i have also included the ImageView, it is not really required but this is just to update you that we can include the other controls also.

& at the last you should have a function in your related class:

private void LoadData()
{

    DBAdapter db = new DBAdapter(this);
    db.open();
    Cursor cur = db.GetData();
    private ListView lv = (ListView)findViewById(R.id.myLayout);
    lv.setAdapter(null);
    if(cur.moveToFirst())
    {
            String[] from = new String[] {"_id","column1"};
            int[] to = new int[] {R.id.col1, R.id.col2};
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.grid_item, cur, from, to);
            lv.setAdapter(adapter);  

     }
       db.close();
         }
}
猫瑾少女 2024-12-24 20:31:36

似乎没有人回答您 contextMenu 问题。要获得与您的列表一起使用的上下文菜单,在调用 ListView yourList = getListView(); 之后,您必须调用 registerForContextMenu(yourList);

并处理您的菜单创建必须实现该方法

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){ 
super.onCreateContextMenu(context, v,menuInfo);
MenuInflater inflater = getMenuInflater();
menu.setHeaderTitle("YOUR TITLE");
menu.setHeaderIcon(R.drawable.YOUR DRAWABLE);
inflater.inflate(R.menu.YOUR_MENU_RESOURCE, menu);
}

然后就可以通过实现该方法来响应点击

@Override public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
 }
 return false; // nothing selected
}

It appears that noone has answered you contextMenu question. To get a context menu to work with your list , after you call ListView yourList = getListView(); you must call registerForContextMenu(yourList);

And to handle the menu creation you must implement the method

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){ 
super.onCreateContextMenu(context, v,menuInfo);
MenuInflater inflater = getMenuInflater();
menu.setHeaderTitle("YOUR TITLE");
menu.setHeaderIcon(R.drawable.YOUR DRAWABLE);
inflater.inflate(R.menu.YOUR_MENU_RESOURCE, menu);
}

Then you can respond to clicks by implenting the method

@Override public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
case R.id.YOUR_MENU_ITEM: // do stuff if the item is selected
 return true;
 }
 return false; // nothing selected
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文