【问题标题】:Adding ListView item from another Layout从另一个布局添加 ListView 项目
【发布时间】:2013-06-09 13:42:48
【问题描述】:

在我的应用中有两个布局 first.xml 和 activity_main.xml。在第一个布局中有一个按钮和 ListView(代码):

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

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

    <ListView
        android:id="@+id/listView_items"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

而且这个Layout是和MainActivty连接的:

package com.example.listview2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView lvItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        Button but = (Button) findViewById(R.id.but);
        lvItem = (ListView)this.findViewById(R.id.listView_items);

        but.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ListActivity.class);
                startActivity(intent);
            }
        });

}
}

然后是第二个布局activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ListActivity" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" 
    android:id="@+id/input">

    <EditText
        android:id="@+id/editText_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Add" />
</LinearLayout>


<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_above="@+id/input"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:orientation="vertical" >

</LinearLayout>

</RelativeLayout>

并且这个activity是连接到ListActivity的:

package com.example.listview2;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ListActivity extends Activity {
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpView();

    }

    private void setUpView() {
        // TODO Auto-generated method stub
        etInput = (EditText)this.findViewById(R.id.editText_input);
        btnAdd = (Button)this.findViewById(R.id.button_add);
        lvItem = (ListView)this.findViewById(R.id.listView_items);


        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        lvItem.setAdapter(itemAdapter);


        btnAdd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                addItemList();
            }
        });

        etInput.setOnKeyListener(new View.OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub

                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    addItemList();
                }
                return true;
            }
        });


    }

    protected void addItemList() {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
    if (isInputValid(etInput)) {
        itemArrey.add(0,etInput.getText().toString());
        etInput.setText("");

        itemAdapter.notifyDataSetChanged();

    }   

    }

    protected boolean isInputValid(EditText etInput2) {
        // TODO Auto-generatd method stub
        if (etInput2.getText().toString().trim().length()<1) {
            etInput2.setError("Please Enter Item");
            return false;
        } else {
            return true;
        }

    }
}

app的想法很简单。当您启动应用程序时,它会启动 MainActivity,它是带有 ListView 的按钮。然后按下按钮打开 ListActivity 以创建新的 ListView 项目,这是我的问题:如何将另一个 Activity 的项目添加到 ListView?

【问题讨论】:

    标签: android android-listview android-activity


    【解决方案1】:

    我认为你的逻辑有点混乱。例如,您在 ListActivity 中引用了一个在其布局中不存在的视图:

    lvItem = (ListView)this.findViewById(R.id.listView_items);
    

    listView_items在first.xml布局中定义,意味着ListActivity中lvItem的引用为空。


    无论如何,以下是设计应用的更好方法:
    1-让您的 MainActivity 充当应用程序的中心组件。由于它正在显示 listView,它还应该负责从中添加/删除项目。当用户想要向列表中添加新项目时,MainActivity 将启动 ListActivity。
    2- 让您的 ListActivity 充当一个简单的界面来获取用户的信息,并将其重新调整到您的 MainActivity。

    在这种情况下,解决方案是使用startActivityForResult()。这是一个小的重写以使其工作:

    公共类 MainActivity 扩展 Activity {

    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first);
        Button but = (Button) findViewById(R.id.but);
        lvItem = (ListView)this.findViewById(R.id.listView_items);
        itemArrey = new ArrayList<String>();
        itemArrey.clear();
    
        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        lvItem.setAdapter(itemAdapter);
    
        but.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ListActivity.class);
                startActivityForResult(intent, 1);
            }
        });
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
           if(resultCode == RESULT_OK){      
               String result=data.getStringExtra("result");
               itemArrey.add(0,result);    
               itemAdapter.notifyDataSetChanged();
           }
           else if (resultCode == RESULT_CANCELED) {    
             //Write your code if there's no result
           }
        }
    }
    }
    

    现在,对于 ListActivity,您将保留相同的代码,但在您的 btnAdd onClickListener 中添加以下内容:

     Intent returnIntent = new Intent();
     returnIntent.putExtra("result",etInput);
     setResult(RESULT_OK,returnIntent);     
     finish();
    

    您显然会想要添加输入验证和其他细节。

    【讨论】:

      【解决方案2】:

      首先你不能这样做

      lvItem = (ListView)this.findViewById(R.id.listView_items);
      

      当你使用 lvItem 时你会得到空指针异常,因为你的activity_main 布局中不存在listView_items。

      使您的设计工作的正确方法是在您为 setResult 创建的意图中将“itemArrey”作为附加包发送回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        相关资源
        最近更新 更多