如何动态地将用户输入添加到片段中的listView中?

时间:2014-09-25 22:14:43

标签: android listview android-fragments

我试图将文本添加到片段中的列表视图中但我不断收到错误:找不到符号方法setListAdapter(ArrayAdapter)。

我使用本教程作为参考,但它只显示了如何在活动中执行此操作:http://wptrafficanalyzer.in/blog/dynamically-add-items-to-listview-in-android/

我试图把它移到片段上。任何人都可以帮忙,我会非常感激吗?继承我的代码:

MainActivity:

import android.app.Activity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;

import com.example.fragments.DeleteDialogueFragment;
import com.example.PeopleFragment;

public class MainActivity extends Activity implements PeopleFragment.PeopleFragmentListener,    DeleteDialogueFragment.DeleteDialogueListener {

private final String TAG = "MAINACTIVITY";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PeopleFragment())
                .commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

//INTERFACE METHODS
public void deleteCharacter(){
    PeopleFragment peopleFragment = (PeopleFragment) getFragmentManager().findFragmentById(R.id.container);
    peopleFragment.deleteCharacter();
}

}

PeopleFragment:

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.example.actionbardemo.R;

import java.util.ArrayList;
import java.util.Arrays;

public class PeopleFragment extends Fragment{

private final String TAG = "PEOPLEFRAGMENT";

private PeopleFragmentListener mListener;
private ArrayAdapter<String> mPeopleAdapter;
private ActionMode mActionMode;
private int mPersonSelected = -1;

/** Items entered by the user is stored in this ArrayList variable */
private ArrayList<String> pList = new ArrayList<String>();

public interface PeopleFragmentListener {

}

public static PeopleFragment newInstance() {
    PeopleFragment fragment = new PeopleFragment();
    return fragment;
}

public PeopleFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<String> people = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.people)));
    mPeopleAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,people);

    // Reference to the button of the layout main.xml
    Button btn = (Button) getView().findViewById(R.id.btnAdd);

    // Defining a click event listener for the button "Add"
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText edit = (EditText) getView().findViewById(R.id.txtItem);
            pList.add(edit.getText().toString());
            edit.setText("");
            mPeopleAdapter.notifyDataSetChanged();
        }
    };
    // Setting the event listener for the add button
    btn.setOnClickListener(listener);

    // Setting the adapter to the ListView
    setListAdapter(mPeopleAdapter);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    ListView peopleList = (ListView) rootView.findViewById(R.id.peopleList);
    peopleList.setAdapter(mPeopleAdapter);
    peopleList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if(mActionMode != null){
                return false;
            }

            mPersonSelected = position;
            mActionMode = getActivity().startActionMode(mActionModeCallback);

            return true;
        }
    });
    return rootView;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (PeopleFragmentListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement PeopleFragmentListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

//INTERFACE METHODS
public void deleteCharacter(){
    mPeopleAdapter.remove(mPeopleAdapter.getItem(mPersonSelected));
    mPeopleAdapter.notifyDataSetChanged();
}

public String getToDelete(){
    return mPeopleAdapter.getItem(mPersonSelected);
}

//CONTEXTUAL ACTION BAR CALLBACK

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

    // Called when the action mode is created; startActionMode() was called
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Inflate a menu resource providing context menu items
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.peoplemenu, menu);
        return true;
    }

    // Called each time the action mode is shown. Always called after onCreateActionMode, but
    // may be called multiple times if the mode is invalidated.
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false; // Return false if nothing is done
    }

    // Called when the user selects a contextual menu item
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.peopleDelete:
                Log.i(TAG,mPeopleAdapter.getItem(mPersonSelected));
                DialogFragment dialog = new DeleteDialogueFragment();
                Bundle args = new Bundle();
                args.putString("name",mPeopleAdapter.getItem(mPersonSelected));
                dialog.setArguments(args);
                dialog.show(getActivity().getFragmentManager(), "DeleteDiaglogueFragment");
                mode.finish();
                return true;
            default:
                return false;
        }
    }

    // Called when the user exits the action mode
    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mActionMode = null;
    }
};

}

activity_main.xml(布局):

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />

fragment_main.xml(布局):

<?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">

<EditText
    android:id="@+id/txtItem"
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:hint="@string/hintTxtItem"/>

<Button
    android:id="@+id/btnAdd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/lblBtnAdd"
    android:layout_toRightOf="@id/txtItem"/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/peopleList"
    android:layout_gravity="center_horizontal" />

</LinearLayout>

的strings.xml(值):

<string name="app_name">ActionBarDemo</string>
<string name="action_settings">Settings</string>
<string name="hintTxtItem">Enter an item here ...</string>
<string name="lblBtnAdd">Add Item</string>
<string name="txtEmpty">List is empty</string>
<string name="delete_confirm">Are you sure you want to delete</string>
<string name="delete">Delete</string>
<string name="cancel">Cancel</string>

<string-array name="people">
    <item>person 1</item>
    <item>person 2</item>
    <item>person 3</item>
    <item>person 4</item>
    <item>person 5</item>
    <item>person 6</item>
</string-array>

0 个答案:

没有答案